Shortest Word Distance

• There an error for the one pass solution minDistance = Math.min(minDistance, Math.abs(i1 - i1)); have to be minDistance = Math.min(minDistance, Math.abs(i1 - i2));

• Thanks! I have corrected it.

• You do not need currentDistance here.

• Check words[i] is word1 or word2, else continue. This can save a little.

• ``````class Solution(object):
def shortestDistanceBF(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
min_dist = len(words)
for i in xrange(len(words)):
if words[i] == word1:
for j in xrange(len(words)):
if words[j] == word2:
min_dist = min(min_dist, abs(i-j))
return min_dist

def shortestDistance(self, words, word1, word2):
i1, i2 = -1, -1
min_dist = len(words)
for i in xrange(len(words)):
if words[i] == word1:
i1 = i
elif words[i] == word2:
i2 = i
if i1 != -1 and i2 != -1:
min_dist = min(min_dist, abs(i1-i2))
return min_dist
``````

• ``````def shortestDistance(self, words, word1, word2):
"""
:type words: List[str]
:type word1: str
:type word2: str
:rtype: int
"""
shortest = len(words)+1
index = None
found = None
for i, word in enumerate(words):
if word == word1 or word == word2:
if found is not None:
if word != found:
shortest = min(shortest, i - index)
found = word
index = i
return shortest``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.