Given an array of strings wordsDict and two strings that already exist in the array word1 and word2, return the shortest distance between the occurrence of these two words in the list.
Note that word1 and word2 may be the same. It is guaranteed that they represent two individual words in the list.
To find the shortest distance between the occurrences of word1 and word2, we can use a linear scan and keep track of the indices of the last occurrences of these words.
classSolution:
defshortestDistance(self, wordsDict: List[str], word1: str, word2: str) -> int:
ans: int = float("inf")
p1: int =-1 p2: int =-1 same_word: bool = word1 == word2
for i, word in enumerate(wordsDict):
if word == word1:
p1 = i
if same_word and p2 !=-1:
ans = min(ans, abs(p1 - p2))
p2 = p1 # Special case: handling same wordelif word == word2:
p2 = i
if p1 !=-1and p2 !=-1andnot same_word:
ans = min(ans, abs(p1 - p2))
return ans