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>& wordDict) {
if(s.size() <= 0) return true;
for(int i = 1;i <= s.size();i++){
if(wordDict.find(s.substr(0,i)) == wordDict.end()) continue;
if(wordBreak(s.substr(i),wordDict)) return true;
}
return false;
}
};
可以用DP解决,dp[i] 要设为true,必须往前遍历,直到dp[j]也为true的时候,把i~j的子串取出,在字典里查询,如果存在,就把dp[i]设为true,否则为false。
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
if(s.empty()) return false;
vector<bool> dp(s.size()+1,false);
dp[0] =true;
for(int i = 1; i <= s.size();i++){
for(int j = i-1; j >=0;j--){
if(dp[j]){
string str = s.substr(j,i-j);
if(wordDict.find(str) != wordDict.end()){
dp[i] = true;
break;
}
}
}
}
return dp[s.size()];
}
};