Shortest Word Distance
Problem: Shortest Word Distance
We can use two variables to store index of latest read two target words so that once we get a new target word, we can update our shortest distance based on these two numbers because we won't achieve shorter distance from earlier pointers.
Code in Python:
class Solution(object):
def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
ans, p1, p2 = len(words), -len(words), -len(words)
for i, word in enumerate(words):
if word == word1: p1, ans = i, min(ans, i-p2)
if word == word2: p2, ans = i, min(ans, i-p1)
return ans