Method that leverage a hashmap in contructor to save time

  • 0

    class WordDistance(object):

    def __init__(self, words):
        :type words: List[str]
        self.word_map = {}
        for i, w in enumerate(words):
            if w in self.word_map:
                self.word_map[w] = [i]
    def shortest(self, word1, word2):
        :type word1: str
        :type word2: str
        :rtype: int
        min_dis = 999999
        for i in self.word_map[word1]:
            for j in self.word_map[word2]:
                min_dis = min(min_dis, abs(i-j))
        return min_dis

Log in to reply

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