Modularized Python Solution O(n)


  • 0

    Not a big fan of the one loop solution. IMO not expressive enough. Don't like how Leetcode is always a competition to have the shortest code. So here goes a modularized solution.

    class Solution(object):
        def shortestWordDistance(self, words, word1, word2):
            if word1 == word2:
                return self.sameWord(words, word1)
            else:
                return self.diffWord(words, word1, word2)
        
        def diffWord(self, words, word1, word2):
            p1 = p2 = -1
            res = sys.maxint
            for i, word in enumerate(words):
                if word == word1:
                    p1 = i
                if word == word2:
                    p2 = i
                if p1 != -1 and p2 != -1:
                    res = min(res, abs(p1-p2))
            return res
    
        def sameWord(self, words, target):
            before = after = -1
            res = sys.maxint
            for i, word in enumerate(words):
                if word == target:
                    if before <= after:
                        before = i
                    elif after < before:
                        after = i
                if before != -1 and after != -1:
                    res = min(res, abs(before-after))
            return res
    

Log in to reply
 

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