244. Shortest Word Distance II
def __init__(self, words):
"""
:type words: List[str]
"""
self.d = collections.defaultdict(list)
for i, w in enumerate(words):
self.d[w].append(i)
def shortest(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
res = float('inf')
d1, d2, i, j = self.d[word1], self.d[word2], 0, 0
while i < len(d1) and j < len(d2):
res = min(res, abs(d1[i] - d2[j]))
if d1[i] < d2[j]:
i += 1
else:
j += 1
return res