python O(n) solution


  • 0
    X
    class Solution(object):
        def shortestWordDistance(self, words, word1, word2):
            """
            :type words: List[str]
            :type word1: str
            :type word2: str
            :rtype: int
            """
            i,j = -1,-1
            dis = float('inf')
            for p,w in enumerate(words):
                if w==word1:
                    if w==word2:
                        if i>-1:
                            j = p
                            dis = min(dis,abs(j-i))
                            i,j = p,-1
                        else:
                            i = p
                    else:
                        i = p
                        if j>-1:
                            dis = min(dis,abs(j-i))
                elif w==word2:
                    j = p
                    if i>-1:
                        dis = min(dis,abs(j-i))
            return dis
    

Log in to reply
 

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