您的位置:首页 > 其它

[leetcode 139]Word Break

2015-08-04 16:52 471 查看
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"
.

对从第一个字符到最后一个字符进行切分,新建一个数组备忘

count[i]=1表示字符串s从第一个字符到弟i个字符可以由字典组成

遍历字符串不断切分,返回count[s.size()]

AC代码

class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int len=s.size();
int sum=wordDict.size();
if(len==0&&sum==0)
return true;
else if(len==0||sum==0)
return false;
int count[len+1];
memset(count,0,sizeof(count));
count[0]=1;
string temp="";
for(int i=1;i<=len;++i)
{
for(int j=i-1;j>=0;--j)
{
temp=s.substr(j,i-j);
if(count[j]&&wordDict.find(temp)!=wordDict.end())
{
count[i]=1;
break;
}
}
}
return count[len];
}
};

其他Leetcode题目AC代码:https://github.com/PoughER/leetcode
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: