方法:dp
dp[i]表示s[0…i] 是否可以用wordDict来表示。
dp[i]=true(存在一个j<i:dp[j] == true && s[j+1…i]在wordDict中存在)
边界:dp[0]=true;
ans:dp[n]
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
int n = s.size();
vector<int> dp(n);
unordered_set<string> hash(wordDict.begin(), wordDict.end());
for (int i = 0; i < n; ++i) {
for (int j = -1; j < i; ++j) {
auto tmp = s.substr(j + 1, i - j);
if ((j == -1 || dp[j]) && hash.count(tmp)) {
dp[i] = true;
break;
}
}
}
return dp[n - 1];
}
};
注意的点:j从-1开始,因为是从j+1开始取子字符串