245. Shortest Word Distance III
Input: word1 = “makes”, word2 = “coding”
Output: 1Input: word1 = "makes", word2 = "makes"
Output: 3解题要点:
class Solution(object):
def shortestWordDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
mydict = collections.defaultdict(list)
for i, k in enumerate(words):
mydict[k].append(i)
loc1 = mydict[word1]
loc2 = mydict[word2]
w1 = w2 = 0
res = sys.maxint
if word1 == word2:
for i in range(len(loc1)-1):
res = min(res, abs(loc1[i+1] - loc1[i]))
else:
while w1 < len(loc1) and w2 < len(loc2):
res = min(res, abs(loc1[w1] - loc2[w2]))
if loc1[w1] < loc2[w2]:
w1 += 1
else:
w2 += 1
return resLast updated