問題描述:
樣例輸入:
代碼如下:
class Solution(object):
def findClosest(self, words , word1="", word2=""):
""" 有個內含單詞的超大文本文件,給定任意兩個不同的單詞, 找出在這個文件中這兩個單詞的最短距離(相隔單詞數)。如果尋找過程在這個文件中會重復多次, 而每次尋找的單詞不同,你能對此優化嗎? :type words: List[str] :type word1: str :type word2: str :rtype: int """
res = len(words)
for i in range(len(words)):
if words[i] == word1:
temp = words[i:]
if temp.count(word2):
a = temp.index(word2)+i
if a-i < res:
res = a-i
elif words[i] == word2:
temp = words[i:]
if temp.count(word1):
a = temp.index(word1)+i
if a - i < res:
res = a - i
return res
if __name__ == '__main__':
res = Solution().findClosest(words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student")
print(res)
結果如下: