leetcode-Word Break
2014-09-27 10:39
267 查看
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s =
dict =
Return true because
class Solution {
public:
bool findWord(vector<vector<bool>> &b, int l, int n, vector<bool> &suffix)
{
if(l == n)
{
return true;
}
if((l != 0)&&(!suffix[l-1]))return false;
for(int i = 0; i < n-l; i++)
{
if(b[i][l])
{
if(findWord(b,l+i+1,n,suffix))return true;
else suffix[l+i] = false;
}
}
return false;
}
bool wordBreak(string s, unordered_set<string> &dict) {
vector<vector<string>>v;
vector<vector<bool>>pal;
vector<vector<string>>ret;
int n = s.length();
if(n==0)return true;
for(int i = 1; i <= n; i++)
{
vector<bool>b;
for(int j = 0; j <= n-i; j++)
{
string s1;
s1.assign(s,j,i);
bool t = false;
if(dict.find(s1) != dict.end()) t = true;
b.push_back(t);
}
pal.push_back(b);
}
vector<bool> suffix;
for(int i = 0; i < n; i++)suffix.push_back(true);
return findWord(pal,0,n,suffix);
}
};
For example, given
s =
"leetcode",
dict =
["leet", "code"].
Return true because
"leetcode"can be segmented as
"leet code".
class Solution {
public:
bool findWord(vector<vector<bool>> &b, int l, int n, vector<bool> &suffix)
{
if(l == n)
{
return true;
}
if((l != 0)&&(!suffix[l-1]))return false;
for(int i = 0; i < n-l; i++)
{
if(b[i][l])
{
if(findWord(b,l+i+1,n,suffix))return true;
else suffix[l+i] = false;
}
}
return false;
}
bool wordBreak(string s, unordered_set<string> &dict) {
vector<vector<string>>v;
vector<vector<bool>>pal;
vector<vector<string>>ret;
int n = s.length();
if(n==0)return true;
for(int i = 1; i <= n; i++)
{
vector<bool>b;
for(int j = 0; j <= n-i; j++)
{
string s1;
s1.assign(s,j,i);
bool t = false;
if(dict.find(s1) != dict.end()) t = true;
b.push_back(t);
}
pal.push_back(b);
}
vector<bool> suffix;
for(int i = 0; i < n; i++)suffix.push_back(true);
return findWord(pal,0,n,suffix);
}
};
相关文章推荐
- [LeetCode]Word Break 字典树
- leetcode笔记:Word Break
- leetcode 139. Word Break
- LeetCode——Word Break
- LeetCode 139. Word Break
- LeetCode:Word Break
- Leetcode: Word Break
- [LeetCode] Word Break
- [LeetCode] word break 字符串的划分
- Leetcode -- Word Break
- leetcode - Word Break
- [LeetCode]Word Break
- leetcode[139] Word Break
- [LeetCode] Word Break
- [Leetcode]Word Break
- [leetcode 139]Word Break
- LeetCode-Word Break
- LeetCode-Word Break
- leetcode 139. Word Break
- leetcode-Word Break