面试题 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:
        # a=words.count(word1)
        # b=words.count(word2)
        # i=0
        # j=len(words)-1
        # ii=jj=0
        # while i<j:
        #     if words[i]==word1:
        #         ii+=1
        #     if words[i]==word2:
        #         jj+=1
        #     if ii==a-1 and jj==b-1:
        #         break
        # return abs(i-j)
        a=[]
        b=[]
        for i in range(len(words)):
            if words[i]==word1:a.append(i)
            if words[i]==word2:b.append(i)
        distance=99999
        for i in a:
            for j in b:
                distance=min(distance,abs(i-j))
        return distance

类似双指针的思想

class Solution:
    def findClosest(self, words: List[str], word1: str, word2: str) -> int:
        i, ans = 0, len(words)
        for j, word in enumerate(words):
            if word==word1 or word == word2:
                if word != words[i] and (words[i] == word1 or words[i] == word2):
                    ans = min(ans, j - i)
                i = j
        return ans

 

posted @ 2020-09-28 16:12  XXXSANS  阅读(364)  评论(0)    收藏  举报