LeetCode 139. Word Break
Solution1:
记忆化递归的典型套路题
参考网址:https://zxi.mytechroad.com/blog/leetcode/leetcode-139-word-break/
class Solution { //记忆化递归!
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> dict(wordDict.begin(), wordDict.end());
return my_word(s, dict);
}
private:
unordered_map<string, bool> word_map;
bool my_word(string s, unordered_set<string>& dict) {
if (word_map.count(s)) return word_map[s]; //已经判断过的子串
if (dict.count(s))
return word_map[s] = true;
for (int i = 1; i < s.size(); i++) {
string temp1 = s.substr(0, i);
string temp2 = s.substr(i);
if (my_word(temp1, dict) && dict.count(temp2))
return word_map[s] = true;
}
return word_map[s] = false;
}
};
Solution2:
此题也是典型的动态规划题目
参考网址:https://www.youtube.com/watch?v=il8Oi21WZN0
时间复杂度:
O(n2−−n3)
O
(
n
2
−
−
n
3
)
空间复杂度:
O(n)
O
(
n
)
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int len = s.length();
unordered_set<string> dict(wordDict.begin(), wordDict.end());
vector<bool> dp(len + 1, false);
s = " " + s;
dp[0] = true;
for (int i = 1; i <= len; i++) {
for (int j = 0; j < i; j++) {
string temp = s.substr(j + 1, i - j);
if (dp[j] && dict.count(temp)) {
dp[i] = true;
break;
}
}
}
return dp[len];
}
};