問題描述:
給定一個非空字符串 s 和一個包含非空單詞列表的字典 wordDict,判定 s 是否可以被空格拆分爲一個或多個在字典中出現的單詞。
說明:
拆分時可以重複使用字典中的單詞。
你可以假設字典中沒有重複的單詞。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/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"]
輸出: false
解題思路:
動態規劃
先將字符串數組存入unorder_set中,
然後雙層循環
判斷字符串i~j這部分能否能在set中找到,並且還要判斷前0·i部分能被切分
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
vector<bool> dp(s.size()+1,false);
unordered_set<string> m(wordDict.begin(),wordDict.end());
dp[0] = true;
int minlen = INT_MAX;
int maxlen =0;
for(auto &str:wordDict){
minlen = min(minlen, (int)str.size());
maxlen = max(maxlen, (int)str.size());
}
for(int i=minlen;i<=s.size();i++){
for(int j=max(0,i-maxlen);j<i;j++){
if(dp[j]&&m.find(s.substr(j,i-j))!=m.end()){
dp[i] = true;
break;
}
}
}
return dp[s.size()];
}
};