Given a string s and a dictionary of words dict, determine if s can be break into a space-separated sequence of one or more dictionary words.
设res[i]表示s的前i个数字母能否分拆后在dict中找到。
则
如果,则res[i]=true;
class Solution {
public:
/**
* @param s: A string s
* @param dict: A dictionary of words dict
*/
bool wordBreak(string s, unordered_set<string> &dict) {
// write your code here
int len=s.size();
if(len==0){
return true;
}
if(dict.size()==0){
return false;
}
int maxLen=0;
for(string str:dict){
if(str.size()>maxLen){
maxLen=str.size();
}
}
vector<bool> res(len+1,false);
res[0]=true;
for(int i=1;i<=len;i++){
for(int j=i-1;j>=0;j--){
if(i-j>maxLen){
break;
}
bool flag=res[j]&& dict.find(s.substr(j,i-j))!=dict.end();
if(flag){
res[i]=true;
break;
}
}
}
return res[len];
}
};