题目描述
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
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
Example1:
Input: s = “leetcode”, wordDict = [“leet”, “code”]
Output: true
Explanation: Return true because “leetcode” can be segmented as “leet code”.
Example2:
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.
Example3:
Input: s = “catsandog”, wordDict = [“cats”, “dog”, “sand”, “and”, “cat”]
Output: false
解题思路
- 经典的dp(子数组或者子字符串且求极值的题,基本就是 DP 没差了,虽然这道题没有求极值,但是玩子字符串也符合 DP 的状态转移的特点。)
- 对于[0, i]来说, 可分为两个部分,[0, j]和[j, i]
- 如果dp[0, j] && substr(j, i - j)在字典里,即可以构成最后的词语dp[i]
- 最后看dp[n]即可
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> wordsets(wordDict.begin(), wordDict.end());
vector<bool> dp(s.size() + 1, false);
dp[0] = true;
for(int i = 0; i <= s.size(); i++){
for(int j = 0; j < i; j++){
dp[i] = dp[i] || (dp[j] && wordsets.count(s.substr(j, i - j)));
}
}
return dp[s.size()];
}
};
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> bag(wordDict.begin(), wordDict.end()); // 还可以这样初始化
/*for(int i = 0; i < wordDict.size(); i++){
bag.insert(wordDict[i]);
}*/ // 往bag里 填充数据
int n = s.size();
bool dp[n + 1] = {false};
dp[0] = true;
for(int i = 0; i < n + 1; i++){
for(int j = 0; j < i; j++){
if(dp[j] && bag.count(s.substr(j, i - j))){
dp[i] = true;
break;
}
}
}
return dp[n];
}
};