sl1673495 / leetcode-javascript

:beers: 喝杯小酒,一起做题。前端攻城狮从零入门算法的宝藏题库,根据知名算法老师的经验总结了 100+ 道 LeetCode 力扣的经典题型 JavaScript 题解和思路。已按题目类型分 label,一起加油。

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

sl1673495 opened this issue · comments

commented

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

示例 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
}