Given a list of words and two wordsword1_and_word2, return the shortest distance between these two words in the list.
For example,
Assume that words =["practice", "makes", "perfect", "coding", "makes"]
.
Givenword1=“coding”
,word2=“practice”
, return 3.
Givenword1="makes"
,word2="coding"
, return 1.
Note:
You may assume thatword1does not equal toword2, and_word1_and_word2_are both in the list.
class Solution {
public int shortestDistance(String[] words, String word1, String word2) {
if (words == null || words.length == 0) return 0;
int index1 = Integer.MIN_VALUE, index2 = Integer.MIN_VALUE;
int ans = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++){
if (words[i].equals(word1)){
if (index2 != Integer.MIN_VALUE){
ans = Math.min(ans, i - index2);
}
index1 = i;
}
else if (words[i].equals(word2)){
if (index1 != Integer.MIN_VALUE){
ans = Math.min(ans, i - index1);
}
index2 = i;
}
}
return ans;
}
}