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的是,可以有重复的元素,如果有重复,那么要分别找到两个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;
}
}