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. 单词拆分 #57

Open
Geekhyt opened this issue Apr 28, 2021 · 0 comments
Open

139. 单词拆分 #57

Geekhyt opened this issue Apr 28, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Apr 28, 2021

原题链接

状态定义

dp[i]: 字符串 s 的前 i 个字符子串 s[0..i-1] 是否由单词表组成。

状态转移方程

dp[i] = dp[j] && check(s[j..i-1])

  • 使用 j 对字符串进行分割,分割成 [0..j-1] (dp[j]) 和 [j, i-1]
  • check(s[j..i-1]):代表子串 s[j..i-1] 是否出现在字典中。

状态转移方程需要满足:

  1. dp[j] 为真
  2. 检查 s[j..i-1] 是否在单词表中

初始化

dp[0] = true,空串且合法。

const wordBreak = function(s, wordDict){
  const wordDictSet = new Set(wordDict)
  const len = s.length
  const dp = new Array(len + 1).fill(false)
  dp[0] = true

  for (let i = 1; i <= len; i++) {
    for (let j = i - 1; j >= 0; j--) {
      const suffix = s.slice(j, i)
      if (wordDictSet.has(suffix) && dp[j]) {
        dp[i] = true
        break
      }
    }
  }
  return dp[len]
}
  • 时间复杂度:O(n^2)
  • 空间复杂度:O(n)
@Geekhyt Geekhyt added the 中等 label Jun 2, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant