My python solution


  • 0
    Y
    # The idea to handle the case word1 == word2 is that p1 and p2 take turns 
    # to pick element that equals to word1 and word2.
    
    def shortestWordDistance(self, words, word1, word2):
        p1 = p2 = float('inf')
        
        turn = 0
        if word1 == word2:
            turn = 1 
        
        result = float('inf')
        for i, w in enumerate(words):
            if w == word1 and turn in (0, 1):
                p1 = i
                if turn == 1:
                    turn = 2
            
            elif w == word2 and turn in (0, 2):
                p2 = i
                if turn == 2:
                    turn = 1
                    
            result = min(abs(p2-p1), result)
            
        return result

Log in to reply
 

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