245. Shortest Word Distance III

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.

解法1:双指针

区别就是当word1和word2相同的时候,退化成只需要一个指针就可以了。在这种情况下,先判断之前是否出现过这个单词,如果出现过计算下当前的距离,然后更新上一次出现的位置。
C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
if (words.length == 0) {
return 0;
}
int left = -1, right = -1;
int res = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1) && word1.equals(word2)) {
if (left != -1) {
res = Math.min(res, i - left);
}
left = i;
} else if (words[i].equals(word1)) {
left = i;
if (right != -1) {
res = Math.min(res, left - right);
}
} else if (words[i].equals(word2)) {
right = i;
if (left != -1) {
res = Math.min(res, right - left);
}
}
}
return res;
}
}