递归,超时
class Solution {
public:
using USET = unordered_set<string>;
bool wordBreak(string s, vector<string>& wordDict) {
USET st;
int minLen = INT_MAX;
int maxLen = INT_MIN;
for (auto& word : wordDict) {
int len = word.size();
if (len > maxLen)
maxLen = len;
if (len < minLen)
minLen = len;
st.insert(word);
}
return reSolver(s, st, minLen, maxLen);
}
private:
bool reSolver(string s, USET& st, int minLen, int maxLen) {
int len = s.size();
if (len == 0) return true;
if (len < minLen) return false;
int i = len;
if (i > maxLen)
i = maxLen;
for (; i >= minLen; --i) {
string substr = s.substr(0, i);
USET::iterator it = st.find(substr);
if (it == cend(st)) continue;
if (reSolver(s.substr(i, len - i), st, minLen, maxLen) == true)
return true;
}
return false;
}
};
动态规划
class Solution {
public:
using USET = unordered_set<string>;
bool wordBreak(string s, vector<string>& wordDict) {
if (wordDict.size() == 0) return false;
USET st;
set<int>lens;
vector<int> dp(s.size() + 1, 0);
for (auto& word : wordDict) {
int len = word.size();
// 有序的
lens.insert(len);
st.insert(word);
}
dp[0] = 1;
for (int i = 1; i <= s.size(); ++i) {
for (auto& len : lens) {
if (i - len < 0) break;
string substr = s.substr(i - len, len);
USET::iterator it = st.find(substr);
if (it == cend(st)) continue;
if (dp[i - len] == 1) {
dp[i] = 1;
break;
}
}
}
return dp[s.size()];
}
};