This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.

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.

For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “makes”, word2 = “coding”, return 1.
Given word1 = "makes", word2 = "makes", return 3.

Note:
You may assume word1 and word2 are both in the list.


题目跟leetcode 243很像,只是word1和word2可以相同了。

用p1, p2两个pointer记录word1,word2最后一次出现的位置。最短路径就是所有|p1 - p2|中的最小值

如果word1跟word2相同,p1指向p2的上一个位置,p2更新为新位置就可以了

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public int shortestWordDistance(String[] words, String word1, String word2) {
int p1 = -1, p2 = -1, min = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1))
p1 = i;
if (words[i].equals(word2)) {
if (word1.equals(word2))
p1 = p2;
p2 = i;
}
if (p1 != -1 && p2 != -1)
min = Math.min(min, Math.abs(p1 - p2));
}
return min;
}

Ref: https://discuss.leetcode.com/topic/20887/12-16-lines-java-c