139. Word Break
Input: s = "leetcode", wordDict = ["leet", "code"]
Output: true
Explanation: Return true because "leetcode" can be segmented as "leet code".Input: s = "applepenapple", wordDict = ["apple", "pen"]
Output: true
Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
Note that you are allowed to reuse a dictionary word.Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
Output: false// Bottom-Up Dynamic programming
bool wordBreak(string s, vector<string>& wordDict) { // time: O(n^3); space: O(n)
unordered_set<string> words(wordDict.begin(), wordDict.end());
int n = s.length();
vector<bool> dp(n + 1, false); // dp[i] means s[0...i - 1] can be broken into segmentations
dp[0] = true;
for (int i = 1; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
if (dp[j] && words.count(s.substr(j, i - j))) {
dp[i] = true;
break;
}
}
}
return dp.back();
}Last updated