Easy python O(n) solution

  • 1
    class Solution(object):
        def shortestWordDistance(self, words, word1, word2):
            :type words: List[str]
            :type word1: str
            :type word2: str
            :rtype: int
            idx1,idx2 = -1,-1
            distance = sys.maxint
            for i in range(len(words)):
                word = words[i]
                if word == word1:
                    idx1 = i
                    if idx2 != -1:
                        if idx1 != idx2:
                            distance = min(distance,idx1-idx2)
                if word == word2:
                    idx2 = i
                    if idx1 != -1:
                        if idx1 != idx2:
                            distance = min(distance,idx2-idx1)
            return distance

    Based on shortest word distance i, just add an if statement to avoid idx1 == idx2, so when word1 == word2, the program will look for different indexes.

Log in to reply

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