This is afollow upofShortest Word Distance. The only difference is nowword1_could be the same as_word2.
Given a list of words and two wordsword1_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"]
.
Givenword1=“makes”
,word2=“coding”
, return 1.
Givenword1="makes"
,word2="makes"
, return 3.
Note:
You may assume_word1_and_word2_are both in the list.
class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
int index = -1;
int min = words.length;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1) || words[i].equals(word2)) {
if (index != -1 && (word1.equals(word2) || !words[index].equals(words[i]))) {
min = Math.min(i - index, min);
}
index = i;
}
}
return min;
}
}