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"
.
Subscribe to see which companies asked this question
解法一:
dp算法,res[i]表示第i个字母(inclusive)之前可以用dictionary中的单词表示。
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int n = s.size();
vector<bool> res(n+1,false);
res[0] = true;
for(int i=1; i<n+1; i++){
for(int j=0; j<i; j++){
if(res[j]&&wordDict.find(s.substr(j,i-j))!=wordDict.end()){
res[i]=true;
break;
}
}
}
return res[n];
}
};