您的位置:首页 > 其它

Leetcode -- Word Break

2015-10-28 14:47 309 查看
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 wordBreak(string s, unordered_set<string>& wordDict) {
int n=s.size();
if(n==0) return 0;
if(wordDict.count(s)>0) return 1;
vector<bool> f(n,0);
string cur,tmp;
for(int i=n-1;i>=0;--i)
{
cur = s.substr(i);
if(wordDict.count(cur)>0) f[i]=1;
else
{
for(int j=i+1;j<n;++j)
{
tmp = s.substr(i,j-i);
if(wordDict.count(tmp)>0&&f[j])
{
f[i]=1;
break;
}
}
}
}
return f[0];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: