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
分析:动态规划,v[i]表示第i个字母不包括这个之前能否被分词;对于比i小的任意一个j,如果j到i的单词在dict内,且v[j]为true,那么v[i]就可以判断为true。
代码:
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
int n=s.size();
vector<bool> v(n+1,false);
v[0]=true;
for(int i=1;i<=n;i++){
for(int j=i-1;j>=0;j--){
if(v[j]&&wordDict.find(s.substr(j,i-j))!=wordDict.end()){
v[i]=true;
break;
}
}
}
return v[n];
}
};