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.
Approach: two case:
1: word1 != word2 , it is simple, some are using i1 = -1, i2 = -1 to check, here I used the distance. Because when checking the min distance, I dont want fake min distance in my result, so I try to expand the initial distance of i1 and i2 be greater than words.length, (but we also cannot use i1 = -1 and i2 = words.length, because the target word might give i2 = 0, then mindistance is 1, which is also fake)
2: word1 == word2, the question becomes how to find the min distance of the indices of a single word. Such as "make" has indices of 0, 3, 5,xxxxx...how to find the min distance. Just use use current i minus last index and keep the global min value.
may assume word1 and word2 are both in the list??????
public int shortestWordDistance(String[] words, String word1, String word2) { if (words == null || words.length == 0) return 0; int i1 = -words.length; //here is to guarantee mindistance will be greater than the word.length int i2 = words.length; int min = Integer.MAX_VALUE; for (int i = 0; i < words.length; i++) { if (!word1.equals(word2)) { if (words[i].equals(word1)) i1 = i; if (words[i].equals(word2)) i2 = i; min = Math.min(min, Math.abs(i1 - i2)); //so we don't have to check if (i1 != -1 && i2 != -1 in other solutions) } else { if (words[i].equals(word1)) { //this the question on how to find the shortest distance of indices of the word min = Math.min(min, Math.abs(i - i1)); //you can change to i - i1, it is also correct i1 = i; // update the i1 with current i for incoming distance checking } } } return min; }