O(n) python solution


  • 0
    S

    I have seen many solutions but none was as simple as a switch.
    If word1 is the same as word2, just make a current copy of the position.

    def shortestWordDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        x, y, distance = sys.maxint, sys.maxint, sys.maxint
        switch = word1 == word2
        for i in range(len(words)):
            if words[i] == word1:
                if switch:
                    y = x 
                x = i
                distance = min(distance, abs(y - x))
            elif words[i] == word2:
                y = i
                distance = min(distance, abs(y - x))
        return distance

Log in to reply
 

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