gary@interview:~/interview/coding/244-shortest-wor….md$
$ cat ./coding/244-shortest-word-distance-ii.md
[Coding]

244. Shortest Word Distance II

────────────────────────────────────────────────────────────

244. Shortest Word Distance II

參考: 243. Shortest Word Distance

class WordDistance:

    def __init__(self, wordsDict: List[str]):
        self.locations = defaultdict(list)

        for i, word in enumerate(wordsDict):
            self.locations[word].append(i)

        

    def shortest(self, word1: str, word2: str) -> int:
        i1 = 0
        i2 = 0
        loc1 = self.locations[word1]
        loc2 = self.locations[word2]
        res = float('inf')

        while i1 < len(loc1) and i2 < len(loc2):
            res = min(res, abs(loc1[i1] - loc2[i2]))
            if loc1[i1] < loc2[i2]:
                i1 += 1
            else:
                i2 += 1
        
        
        return res
        


# Your WordDistance object will be instantiated and called as such:
# obj = WordDistance(wordsDict)
# param_1 = obj.shortest(word1,word2)
--tags#Two Pointers#Hash Table
$ ls ./coding/ | grep -v 244-shortest-word-distance-ii
265. Paint House II256. Paint House143. Reorder List1762. Buildings With an Ocean View
← cd ../codingcd ~