方法一:递归。
Time Limit Exceeded
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
if(s.length() < 1) {
return true;
}
bool flag = false;
for(int i = 1; i <= s.length(); ++i) {
string temp = s.substr(0, i);
unordered_set<string>::iterator it = wordDict.find(temp);
if(it != wordDict.end()) {
if(temp.length() == s.length()) {
return true;
}
flag = wordBreak(s.substr(i), wordDict);
}
if(flag) {
return true;
}
}
return false;
}
};
方法二:DP。
看Discuss中的思路。经典。
用dp[i]记录原串s[0…i-1]是否可以被切分。dp[0]是说初始情况下认为空串可以被切分。
class Solution {
public:
bool wordBreak(string s, unordered_set<string>& wordDict) {
if(wordDict.size() == 0) 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 temp = s.substr(j, i - j);
if(wordDict.find(temp) != wordDict.end()) {
dp[i] = true;
break;
}
}
}
}
return dp[s.size()];
}
};