139.Word Break
示例 1:
输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
示例 2:
输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
注意你可以重复使用字典中的单词。
示例 3:
输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: falseclass Solution {
private:
unordered_map<string,int> dict;
bool dictbreak(string s)
{
if(dict[s]) return true;
for(int i=1;i<s.length();i++)
{
string tmp=s.substr(0,i);
if(dict[tmp] && dictbreak(s.substr(i,s.length()-i)))
return true;
}
return false;
}
public:
bool wordBreak(string s, vector<string>& wordDict) {
for(int i=0;i<wordDict.size();i++)
dict[wordDict[i]]++;
return dictbreak(s);
}
};Last updated