标签:leetcode dp 139 word break
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 dp 139 word break
原文地址:http://blog.csdn.net/er_plough/article/details/47279197