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.
一刷
題解:不同于243的是,可以有重復(fù)的元素,如果有重復(fù),那么要分別找到兩個index, 并比較差值。
如果word1和word2相等,那么如果找到
p1 = p2;
p2 = i;
類似于隊列,保存相鄰的index, 從而比較差值。
如果word1和word2不等,則分別對p1, p2賦值。
public class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
boolean same = word1.equals(word2);
int min = Integer.MAX_VALUE;
int p1 = -1, p2 = -1;
for(int i=0; i<words.length; i++){
if(words[i].equals(word1)){
if(same){
p1 = p2;
p2 = i;
}
else{
p1 = i;
}
}
if(!same && words[i].equals(word2)) p2 = i;
if(p1!=-1 && p2!=-1) min = Math.min(min, Math.abs(p1-p2));
}
return min;
}
}