# 244. Shortest Word Distance II

**<font color=red>难度: Medium</font>**

## 刷题内容

> 原题连接

* https://leetcode.com/problems/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.
```

## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(k^2)******


sb题目没什么好说的, beats 93.02%


```python
class WordDistance:

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

    def shortest(self, word1, word2):
        """
        :type word1: str
        :type word2: str
        :rtype: int
        """
        lst1 = self.lookup[word1]
        lst2 = self.lookup[word2]
        res = sys.maxsize
        for i in lst1:
            for j in lst2:
                res = min(res, abs(i-j))
        return res
```
