# 30 Day Challenge Day 21 | Leetcode 139. Word Break

## 题解

Medium

class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
// a + b = s
// as long as a true and b true, then s true
// dp[i]: i represents the sub string from 0 to i
// find dp[n-1]
vector<bool> dp(s.size()+1, false);
dp[0] = true; // assume an empty word is always existing in dict

for(int i = 1; i <= s.size(); i++) {
for(int j = 0; j < i; j++) {
if(dp[j] && find(wordDict.begin(), wordDict.end(), s.substr(j, i-j)) != wordDict.end()) {
dp[i] = true;
break;
}
}
}

return dp[s.size()];
}
};


class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set wordSet(wordDict.begin(), wordDict.end());
vector<int> memo(s.size(), -1);
return helper(s, wordSet, 0, memo);
}

bool helper(string s, unordered_set<string>& wordSet, int start, vector<int>& memo) {
// memo[i]: the substring form i to size-1
if(start == s.size()) return true; // empty word

// first check if this has been solved before
if(memo[start] != -1) return memo[start];

// divide problem into start to i, and i to end
for(int i = start; i <= s.size(); i++) {
if(wordSet.count(s.substr(start, i-start)) && helper(s, wordSet, i, memo)) {
memo[start] = 1;
return true;
}
}

memo[start] = 0;
return false;
}
};

posted @ 2020-10-09 02:00  CasperWin  阅读(78)  评论(0编辑  收藏  举报