Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

245. Shortest Word Distance III #112

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

public class Solution { public int shortestWordDistance(String[] words, String word1, String word2) { //word1,word2内存地址是不同的,所以==得出结果为false int index1 = -1, index2 = -1; int distance = Integer.MAX_VALUE; for(int i = 0; i < words.length; i++) { if(word1.equals(word2)) { if(words[i].equals(word1)) { if(index1 == -1) { index1 = i; } else if(index2 == -1) { index2 = i; } else { index1 = index2; index2 = i; } } } else { //此处不能用==,因为取地址只来比较 if(words[i].equals(word1)) index1 = i; if(words[i].equals(word2)) index2 = i; } if(index1 != -1 && index2 != -1) //Math.abs()取绝对值 distance = Math.min(distance, Math.abs(index1-index2)); } return distance; } }

Shawngbk commented 7 years ago

Linkedin