Python solution with comments.


  • 0
    C
    def shortestWordDistance(self, words, word1, word2):
        p1 = p2 = -1
        res = len(words)
        # first case: the same as Shortest Word Distance
        if word1 != word2:
            for i, w in enumerate(words):
                if w == word1:
                    p1 = i
                if w == word2:
                    p2 = i
                if p1 > -1 and p2 > -1:
                    res = min(res, abs(p1-p2))
            return res
        else:
            # pre and i record previous and current word1 respectively
            pre, i = -len(words), 0
            while i < len(words):
                while i < len(words) and words[i] != word1:
                    i += 1
                if i < len(words):
                    res = min(res, i-pre)
                pre = i
                i += 1
            return res

Log in to reply
 

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