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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章