245. Shortest Word Distance III
比1多了一个判断是不是相同的
1 public int shortestWordDistance(String[] words, String word1, String word2) { 2 boolean same = word1.equals(word2); 3 int idx1 = -1; 4 int idx2 = -1; 5 int min = Integer.MAX_VALUE; 6 for(int i = 0; i < words.length; i++) { 7 if(word1.equals(words[i])) { 8 if(same) { 9 if(idx1 < idx2) { 10 idx1 = i; 11 } else { 12 idx2 = i; 13 } 14 } else { 15 idx1 = i; 16 } 17 } else if(word2.equals(words[i])) { 18 idx2 = i; 19 } 20 if(idx1 != -1 && idx2 != -1) { 21 min = Math.min(min, Math.abs(idx1 - idx2)); 22 } 23 } 24 return min; 25 }