244. Shortest Word Distance II

Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters.

Example: Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1

Note: You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

解题要点:

用dict套list来存index,然后在word1的list和word2的list里找哪两个相邻最近。

class WordDistance(object):

    def __init__(self, words):
        """
        :type words: List[str]
        """
        self.words = collections.defaultdict(list)
        for i, k in enumerate(words):
            self.words[k].append(i)

    def shortest(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        l1 = self.words[word1]
        l2 = self.words[word2]
        w1 = w2 = 0
        res = sys.maxint
        while w1 < len(l1) and w2 < len(l2):
            res = min(res, abs(l1[w1] - l2[w2]))
            if l1[w1] < l2[w2]:
                w1 += 1
            else:
                w2 += 1
        return res

# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(words)
# param_1 = obj.shortest(word1,word2)

Last updated

Was this helpful?