245. Shortest Word Distance III
Approach 1: Storing list of indices of both words
class Solution(object):
def shortestWordDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
word1s = []
word2s = []
for i in range(len(words)):
if words[i] == word1:
word1s.append(i)
if words[i] == word2:
word2s.append(i)
mi = float('inf')
for i in word1s:
for j in word2s:
if i != j:
mi = min(abs(i-j), mi)
return miApproach 2: Iterating through list but storing only last seen index of each word
Last updated