Easy Python Solution


  • 0
    class Solution(object):
        def shortestWordDistance(self, words, word1, word2):
            """
            :type words: List[str]
            :type word1: str
            :type word2: str
            :rtype: int
            """
            h = collections.defaultdict(list)
            for i in range(len(words)):
                h[words[i]].append(i)
            a, b = h[word1], h[word2]
            minlen = sys.maxint
            for x in a:
                for y in b:
                    if x != y:
                        minlen = min(abs(x-y),minlen)
            return minlen

Log in to reply
 

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