代码随想录算法打卡第四十天, 新手自我记录一下刷题历程, 仅为自我打卡使用.
139. 单词拆分
class Solution {
public:
bool check(string& a, string& s, int start) {
for (int i = 0; i < a.size(); ++i) {
if (a[i] != s[i + start])
return false;
}
return true;
}
bool wordBreak(string s, vector<string>& wordDict) {
vector<int> dp(s.size() + 1, 0);
for (int j = 1; j <= s.size(); ++j) {
for (int i = 0; i < wordDict.size(); ++i) {
if (j >= wordDict[i].size() && check(wordDict[i], s, dp[j - wordDict[i].size()])) {
dp[j] = max(dp[j], int(dp[j - wordDict[i].size()] + wordDict[i].size()));
}
}
}
if (dp.back() == s.size()) return true;
else return false;
}
};