Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
Note:
Example 1:
Input: s = "leetcode", wordDict = ["leet", "code"] Output: true Explanation: Return true because "leetcode" can be segmented as "leet code".
Example 2:
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.
Example 3:
Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"] Output: false
Approach #1:
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> _wordDict(wordDict.begin(), wordDict.end());
return wordBreak(s, _wordDict);
}
bool wordBreak(const string& s, const unordered_set<string>& wordDict) {
if (memo_.count(s)) return memo_[s];
if (wordDict.count(s)) return memo_[s] = true;
for (int j = 1; j < s.length(); ++j) {
string left = s.substr(0, j);
string right = s.substr(j);
if (wordDict.count(right) && wordBreak(left, wordDict))
return memo_[s] = true;
}
return memo_[s] = false;
}
private:
unordered_map<string, bool> memo_;
};
原文:https://www.cnblogs.com/ruruozhenhao/p/10367558.html