Leetcode C++《每日一题》20200625 139. 单词拆分
1. 题目
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。
说明:
拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/word-break
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.思路
- 其实就是wordDict里面的单词多次组合,能不能组合成s
- dp[i][j] 表示[i,j]是否可以用wordDict组成,但是由小及大,i和j都变化的话有点困难
- dp[i]可以由比它小的index过度过来 dp[i] = true, if (dp[j]=true , s(j+1, i) in wordDict)
3.代码
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
//其实就是wordDict里面的单词多次组合,能不能组合成s
//dp[i][j] 表示[i,j]是否可以用wordDict组成,但是由小及大,i和j都变化的话有点困难
//dp[i]可以由比它小的index过度过来 dp[i] = true, if (dp[j]=true , s(j+1, i) in wordDict)
unordered_map<string, bool> mark;
for (int i = 0; i < wordDict.size(); i++) {
if (!mark.count(wordDict[i]))
mark[wordDict[i]] = true;
}
bool* dp = new bool[s.length()+1];
dp[0] = true;
for (int i = 0 ; i < s.length(); i++) {
// dp[i+1],表示s[0,i+1)是否可以被组成
bool flag = false;
for (int j = 0; j <= i; j++) {
if (dp[j] && mark.count(s.substr(j,i-j+1))) {
flag = true;
break;
}
}
dp[i+1] = flag;
//cout << i+1 << " " << dp[i+1] << endl;
}
return dp[s.length()];
}
};
4.debug
- 基本case没有过,因为没有理解dp的index和s的index之间的含义
- 打印case的每一个dp值发现,2层循环j少算了一次