问题描述:
样例输入:
代码如下:
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)
结果如下: