问题描述:
给你一个字符串 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" 拼接成。
注意,你可以重复使用字典中的单词。
解题思路:动态规划
-
定义数组dp,长度为s.length + 1,dp[i]表示s的前i位是否可以用wordDict表示
-
初始情况:dp[0] = true
-
确定状态转移方程:
代码实现(js)
/**
* @param {string} s
* @param {string[]} wordDict
* @return {boolean}
*/
var wordBreak = function(s, wordDict) {
// 1.定义数组dp,长度为s.length + 1,dp[i]表示s的前i位是否可以用wordDict表示
let dp = new Array(s.length + 1).fill(false)
dp[0] = true
// 2.遍历
for(let i = 0; i < s.length; i++){
for(let j = i; j < s.length + 1; j++){
if(dp[i] && wordDict.includes(s.substring(i, j))){
dp[j] = true
}
}
}
return dp[s.length]
};