Easy Python Solution

  • 0
    class WordDistance(object):
        def __init__(self, words):
            initialize your data structure here.
            :type words: List[str]
            self.h = collections.defaultdict(list)
            for i in range(len(words)):
        def shortest(self, word1, word2):
            Adds a word into the data structure.
            :type word1: str
            :type word2: str
            :rtype: int
            minlen = sys.maxint
            for x in self.h[word1]:
                for y in self.h[word2]:
                    minlen = min(abs(x-y), minlen)
            return minlen
    # Your WordDistance object will be instantiated and called as such:
    # wordDistance = WordDistance(words)
    # wordDistance.shortest("word1", "word2")
    # wordDistance.shortest("anotherWord1", "anotherWord2")

Log in to reply

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