您的位置:首页 > 其它

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 = 
"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);

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: