class Solution:
def findClosest(self, words: List[str], word1: str, word2: str) -> int:
# 字典存储每个词的出现的所有位置
dic = {}
for i,word in enumerate(words):
if word not in dic:
dic[word] = []
dic[word].append(i)
L1,L2 = dic[word1],dic[word2]
p1,p2 = 0,0
n1,n2 = len(L1),len(L2)
res = len(words)
while p1 < n1 and p2 < n2:
# print(p1,n1,p2,n2)
res = min(res,abs(L1[p1]-L2[p2]))
if L1[p1] < L2[p2]:
p1 += 1
else:
p2 += 1
return res
每日一道Leetcode -面试题 17.11. 单词距离 [字典|双指针]
最新推荐文章于 2022-05-27 09:19:53 发布