【leetcode】-两个单词的最短距离(相隔单词数)

173 阅读1分钟

题目

有个内含单词的超大文本文件,给定任意两个单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此进行优化吗?

示例

示例1:
输入: words = ['It', 'is', 'very', 'nice', 'of', 'you'], word1 = 'It', word2 = 'nice'
输出: 3
提示: 2 <= words.length <= 100000
注意: 你可以假设 word1 和 word2 都在列表里。

题解

// ◆封装获取两个单词的最短距离的函数
const shortWordDistance = (words, word1, word2) => {
    let len = words.length
    let i = 0
    let res = Infinity
    let index1 = -1
    let index2 = -1
    while (i < len) {
        if (words[i] == word1) {
            index1 = i
        }
        if (words[i] == word2) {
            index2 = i
        }
        if (index1 != -1 && index2 != -1) {
            res = Math.min(res, Math.abs(index1 - index2))
        }
        i++
    }
    return res
}

// ◆测试用例
let words = ['It', 'is', 'very', 'nice', 'of', 'you'], word1 = 'It', word2 = 'nice'
console.log(shortWordDistance(words, word1, word2)) // 3