More Understandable Python Codes


  • 0
    N

    Key point: only update one pointer each time

     def shortestWordDistance(self, words, word1, word2):
            p1, p2 = -1, -1
            ret = sys.maxint
                
            for i in range(len(words)):
                word = words[i]
                
                if word == word1:
                    if word == word2:
                        p2 = p1
                    p1 = i
    
                elif word == word2:
                    if word == word1:
                        p1 = p2
                    p2 = i
    
                if p1 != -1 and p2 != -1:
                    ret = min(ret, abs(p1 - p2))
                    
            return ret

  • 0
    A
     elif word == word2:
        if word == word1:
    

    This if block seems to be redundant and unreachable.


Log in to reply
 

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