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"
.
好吧,其实,看来,是一道简单题,之前也想到了dp,但是没有想到第一步,即确定字典里面最长的字符串
f(i) = for(j=1;j<len;j++) f(i-j)&&find(s.substr(i-j,j))
class Solution {
public:
bool find(string s,unordered_set<string> &dict){
unordered_set<string>::iterator it = dict.find(s);
return it!=dict.end();
}
bool wordBreak(string s, unordered_set<string> &dict) {
int len=0;
string str;
for(unordered_set<string>::iterator it = dict.begin();it!=dict.end();it++){
str = *it;
len = max((int)str.length(),len);
}
bool *f = new bool[s.length()+1];
f[0] = true;
for(int i=0;i<s.length();i++){
for(int j=1;i+1-j>=0 && j<=len;j++){
f[i+1] = f[i+1-j] && find(s.substr(i+1-j,j),dict);
if(f[i+1])
break;
}
}
return f[s.length()];
}
};