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> &dict) {
if(!s.size()) return false;
vector<int> satisfied(s.size(),0);//记录s[0-i]是否可以分词
for(size_t i=0;i<s.size();++i){
string ts = s.substr(0,i+1);
unordered_set<string>::iterator iter= dict.find(ts);
if(iter!=dict.end()){
satisfied[i]=1;
}else{
for(size_t j=0;j<i;++j){
if(!satisfied[j]) continue;
iter = dict.find(s.substr(j+1,i-j));
if(iter!=dict.end()){
satisfied[i]=1;
break;
}
}
}
}
return satisfied[s.size()-1];
}
};