leetcode-面试题 17.11. 单词距离

问题:

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

示例:

输入:words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student" 输出:1
提示:

words.length <= 100000

思路:

查找这两个单词的位置,通过双指针定位。

代码:

class Solution:
    def findClosest(self, words: List[str], word1: str, word2: str) -> int:
        ind1 = 0
        ind2 = 0
        dis = 100000
        
        for i in range(len(words)):
            if word1 == words[i]:
                ind1 = i
            elif word2 == words[i]:
                ind2 = i
            
            if ind1 != 0 and ind2 != 0:
                tmp = abs(ind1 - ind2)
                if tmp < dis:
                    dis = tmp
        return dis

猜你喜欢

转载自blog.csdn.net/xinxiang7/article/details/107075945