LeetCode刷题 Day46
139. Word Break
Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
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
思路: 因为wordDict中的word是可以重复使用的,所以是一个完全背包问题
步骤:
- dp的index和value: index 是背包大小,value是在当前位置下是否可以填满背包,true/false
- 递推公式: 当满足s.slice(i - word.length, i) === word && dp[i - word.length]的时候, dp[i] = true;
- 初始化: dp[0] = true,其余为false可以理解成当背包为空的时候,空字符串即可满足条件
- 遍历顺序: 虽然是完全背包,但不是计算排列组合问题,内外顺序没有影响。
- 举例:
代码:
var wordBreak = function(s, wordDict) {
let dp = Array(s.length + 1).fill(false);
dp[0] = true;
for (let i = 0; i <= s.length; i++) {
for (let word of wordDict) {
if (i >= word.length) {
let tempWord = s.slice(i - word.length, i);
if (tempWord === word && dp[i - word.length]) {
dp[i] = true;
}
}
}
}
return dp[s.length];
};
时间复杂度: O(mn), 空间复杂度: O(n)