https://leetcode.com/problems/word-break/description/
没啥说的把,dp[i] = dp[k] & substr(k~i)在dict里面
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set <string> dict;
int tot_len = 0;
for (int i = 0; i < wordDict.size(); i++) {
dict.insert( wordDict[i] );
tot_len += wordDict[i].size();
}
bool dp[s.size() + 1];
for (int i = 0; i < s.size(); i++) {
dp[i] = false;
for (int k = 0; k <= i; k ++) {
if (k>=1?dp[k-1]:true) {
dp[i] |= (bool) ( dict.count( s.substr(k, i - k + 1) ) );
}
}
}
return dp[s.size()-1];
}
};
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict, int ptr) {
if(ptr == s.size()) return true;
// bool rslt = false;
for(int i = 0; i < wordDict.size(); i++) {
if(ptr+wordDict[i].size() > s.size()) continue;
string sub = s.substr(ptr, wordDict[i].size());
// if(sub)
if(sub == wordDict[i] && wordBreak(s, wordDict, ptr+wordDict[i].size())) return true;
}
return false;
}
bool wordBreak(string s, vector<string>& wordDict) {
// sort(wordDict.begin(), )
// reverse(wordDict.begin(), wordDict.end());
// return wordBreak(s, wordDict, 0);
bool dp[s.size()+1];
// dp[0] = 1;
for(int i = 0; i < s.size(); i++) {
dp[i] = 0;
for(int k = 0; k < wordDict.size(); k++) {
if(i + 1>=(int) wordDict[k].size()) {
if(s.substr(i-wordDict[k].size()+1, wordDict[k].size()) == wordDict[k]) {
if(i + 1 == (int)wordDict[k].size())
dp[i] = 1;
// cout << (i - (int)wordDict[k].size() >= 0) << "**" << i - (int)wordDict[k].size() << "i:" << i << " v:" << wordDict[k].size() << endl;
if(i - (int)wordDict[k].size() >= 0) {
dp[i] = dp[i] | dp[i-wordDict[k].size()];
}
if(dp[i]) break;
}
}
}
// printf("dp[%d]=%d\n", i, dp[i]);
}
return dp[s.size()-1];
}
};