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

通过删除字母匹配到字典里最长单词-524 #98

Open
sl1673495 opened this issue Jun 26, 2020 · 0 comments
Open

通过删除字母匹配到字典里最长单词-524 #98

sl1673495 opened this issue Jun 26, 2020 · 0 comments

Comments

@sl1673495
Copy link
Owner

sl1673495 commented Jun 26, 2020

给定一个字符串和一个字符串字典,找到字典里面最长的字符串,该字符串可以通过删除给定字符串的某些字符来得到。如果答案不止一个,返回长度最长且字典顺序最小的字符串。如果答案不存在,则返回空字符串。

示例 1:

输入:
s = "abpcplea", d = ["ale","apple","monkey","plea"]

输出:
"apple"
示例 2:

输入:
s = "abpcplea", d = ["a","b","c"]

输出:
"a"
说明:

所有输入的字符串只包含小写字母。
字典的大小不会超过 1000。
所有输入的字符串长度不会超过 1000。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-word-in-dictionary-through-deleting
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

为数组 d 中的每个单词分别生成指针,指向那个单词目前已经匹配到的字符下标。然后对 s 进行一次遍历,每轮循环中都对 d 中所有指针的下一位进行匹配,如果匹配到了,则那个单词的指针后移。

一旦某个单词指针移动到那个字母的最后一位了,就和全局的 find 变量比较,先比较长度,后比较字典序,记录下来,最后返回即可。

/**
 * @param {string} s
 * @param {string[]} d
 * @return {string}
 */
let findLongestWord = function (s, d) {
  let n = d.length
  let points = Array(n).fill(-1)

  let find = ""
  for (let i = 0; i < s.length; i++) {
    let char = s[i]
    for (let j = 0; j < n; j++) {
      let targetChar = d[j][points[j] + 1]
      if (char === targetChar) {
        points[j]++
        let word = d[j]
        let wl = d[j].length
        if (points[j] === wl - 1) {
          let fl = find.length
          if (wl > fl || (wl === fl && word < find)) {
            find = word
          }
        }
      }
    }
  }

  return find
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant