# 245. Shortest Word Distance III

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MaqKqvdq7loJ7-u1FEu%2F-Mar3XHJkZ1YEasifjqr%2Fimage.png?alt=media\&token=b9fa5e9c-97f2-4fd6-babf-58e30af334da)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MaqKqvdq7loJ7-u1FEu%2F-Mar3ePoREvdwHYpkcgF%2Fimage.png?alt=media\&token=11ecf487-1e3e-4c83-bed8-e1932a2d6180)

time: O(n)

space: O(1)



**Example 2:**

```
Input: wordsDict = ["practice", "makes", "perfect", "coding", "makes"],
word1 = "makes", word2 = "makes"
makes index [1, 4]
Output: 3
```

```java
class Solution {
    public int shortestWordDistance(String[] wordsDict, String word1, String word2) {
        int a = -1;
        int b = -1;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < wordsDict.length; i++) {
            if (wordsDict[i].equals(word1)) {
                a = i;// first match: 1, second match: 4
            }
            if (wordsDict[i].equals(word2)) { // 243 + only add this
                if (word1.equals(word2)) { // 243 + only add this
                    a = b; // first match: a = 1 => a = -1(b), second match: -1 => 1(b)
                }
                b = i;// orign: -1, first match: 1, second match: 4
            }
            if (a != -1 && b != -1) {
                min = Math.min(min, Math.abs(a - b));
            }
        }
        return min;
    }
}
```



if use 244... 應該只要多加這個判斷, 同樣的 word1  word2, 最小距離會在相臨的

```
        if (word1.equals(word2)) {
            for (int i = 0; i < data1.size() - 1; i++) {           
                min = Math.min(min, Math.abs(data1.get(i) - data1.get(i+1)));          
            }
            return min;
        }
```
