244. Shortest Word Distance II
Input: word1 = “coding”, word2 = “practice”
Output: 3Input: word1 = "makes", word2 = "coding"
Output: 1解题要点:
class WordDistance(object):
def __init__(self, words):
"""
:type words: List[str]
"""
self.words = collections.defaultdict(list)
for i, k in enumerate(words):
self.words[k].append(i)
def shortest(self, word1, word2):
"""
:type word1: str
:type word2: str
:rtype: int
"""
l1 = self.words[word1]
l2 = self.words[word2]
w1 = w2 = 0
res = sys.maxint
while w1 < len(l1) and w2 < len(l2):
res = min(res, abs(l1[w1] - l2[w2]))
if l1[w1] < l2[w2]:
w1 += 1
else:
w2 += 1
return res
# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(words)
# param_1 = obj.shortest(word1,word2)Last updated