Shortest Word Distance III
Problem: Shortest Word Distance III
To deal with distance between same words, we can swap word1 and word2 so that we can deal same words as different word.
Code in Python:
class Solution(object):
def shortestWordDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
ans, i1, i2 = len(words), -len(words), -len(words)
for i, word in enumerate(words):
if word == word1:
ans, i1 = min(ans, i-i2), i
word1, word2 = word2, word1
i1, i2 = i2, i1
elif word == word2:
ans, i2 = min(ans, i-i1), i
return ans