# 245. Shortest Word Distance III

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

## 刷题内容

> 原题连接

* https://leetcode.com/problems/shortest-word-distance-iii/

> 内容描述

```
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

word1 and word2 may be the same and they represent two individual words in the list.

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

Input: word1 = “makes”, word2 = “coding”
Output: 1
Input: word1 = "makes", word2 = "makes"
Output: 3
Note:
You may assume word1 and word2 are both in the list.
```

## 解题方案

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

跟Shortest Word Distance I 没啥区别，就加了个word1和word2相等的情况

beats 50.23%

```python
class Solution(object):
    def shortestWordDistance(self, words, word1, word2):
        """
        :type words: List[str]
        :type word1: str
        :type word2: str
        :rtype: int
        """
        lookup = collections.defaultdict(list)
        for idx, word in enumerate(words):
            lookup[word].append(idx)
            
        if word1 == word2:
            idxes = lookup[word1]
            res = sys.maxsize
            for i in range(len(idxes)):
                for j in range(i+1, len(idxes)):
                    res = min(res, abs(idxes[i]-idxes[j]))
            return res
            
        idxes_1 = lookup[word1]
        idxes_2 = lookup[word2]
        res = sys.maxsize
        for i in idxes_1:
            for j in idxes_2:
                res = min(res, abs(i-j))
        return res
```
