题目链接:面试题 17.11. 单词距离
用双指针遍历两个列表,可以在遍历一次的情况下,找到两个单词的最近距离。
如果只需要单次寻找,无需维护一个字典,可以直接遍历 words 一次即可。
from collections import defaultdict
from typing import List
class Solution:
def findClosest(self, words: List[str], word1: str, word2: str) -> int:
index = defaultdict(list)
for i, word in enumerate(words):
index[word].append(i)
if not index[word1] or not index[word2]:
return -1
if word1 == word2:
return 0
i, j, closest = 0, 0, len(words)
while i < len(index[word1]) and j < len(index[word2]):
diff = index[word1][i] - index[word2][j]
closest = min(closest, abs(diff))
if diff > 0:
j += 1
elif diff < 0:
i += 1
return closest