Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

139. 单词拆分 #49

Open
webVueBlog opened this issue Sep 4, 2022 · 0 comments
Open

139. 单词拆分 #49

webVueBlog opened this issue Sep 4, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

139. 单词拆分

Description

Difficulty: 中等

Related Topics: 字典树, 记忆化搜索, 哈希表, 字符串, 动态规划

给你一个字符串 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

提示:

  • 1 <= s.length <= 300
  • 1 <= wordDict.length <= 1000
  • 1 <= wordDict[i].length <= 20
  • swordDict[i] 仅有小写英文字母组成
  • wordDict 中的所有字符串 互不相同

Solution

Language: JavaScript

/**
 * @param {string} s
 * @param {string[]} wordDict
 * @return {boolean}
 */
// 动态规划
// dp[i]: 子串s[0, i]是否满足,为boolean
// dp[i]初始化:除了dp[0]为true,其他为false
// 从0到n遍历字符串,判断当前dp[i]含义是否满足
// 在判断当前dp[i]中,从0到i遍历分隔点j
// 1.若[0,j]满足,且剩下的在wordDict中出现过,则当前[0,i]子串就满足
// 2.若当前[0,i]子串满足,就不用继续遍历当前子串的分隔点了,跳过,判断下一轮子串[0, i+1]
const wordBreak = (s, wordDict) => {
    const n = s.length
    const set = new Set(wordDict)
    // dp初始化,除了第一个,全为false
    const dp = new Array(n + 1).fill(false)
    dp[0] = true

    // 从1到n遍历s
    for (let i = 1; i <= n; i++) {
        // 当遍历到i时,再从0到i遍历
        for (let j = 0; j < i; j++) {
            // 当前i所处的子串是否可以,取决于分隔点j
            // 对于分隔点j,若[0,j]满足,且剩下的在wordDict中出现过,则当前[0,i]子串就满足
            if (dp[j] && set.has(s.slice(j , i))) {
                dp[i] = true
                // 若当前[0, i] 子串满足,就不用继续遍历当前子串的分隔点了
                // 跳过,判断下一轮子串[0,i+1]
                break
            }
        }
    }
    return dp[n]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant