Shortest Word Distance II

Problem: Shortest Word Distance II

We can construct a hash table which stores indexes of characters in a list. Then, we check all the indexes of word 1 and word 2 to achieve our answer.

Code in Python:

class WordDistance(object):
    def __init__(self, words):
        """
        initialize your data structure here.
        :type words: List[str]
        """
        self.dict = {}
        for i, word in enumerate(words):
            if word not in self.dict: self.dict[word] = [i]
            else: self.dict[word].append(i)


    def shortest(self, word1, word2):
        """
        Adds a word into the data structure.
        :type word1: str
        :type word2: str
        :rtype: int
        """
        ans = 2**31
        for i in self.dict[word1]:
            for j in self.dict[word2]:
                ans = min(ans, abs(i-j))
        return ans

results matching ""

    No results matching ""