245 Shortest Word Distance III
from collections import defaultdict
import sys
class Solution:
def shortestWordDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
self.d = defaultdict(list)
for i, word in enumerate(words):
self.d[word].append(i)
dist = sys.maxsize
for loc1 in self.d[word1]:
for loc2 in self.d[word2]:
if loc1 != loc2:
dist = min(dist, abs(loc1 - loc2))
return distLast updated