1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class Solution { public int shortestDistance(String[] words, String word1, String word2) { int index1 = -1; int index2 = -1; int minDis = Integer.MAX_VALUE; for (int i = 0; i < words.length; i++){ if (words[i].equals(word1)){ index1 = i; }else if (words[i].equals(word2)){ index2 = i; } if (index1 != -1 && index2 != -1){ minDis = Math.min(minDis, Math.abs(index1-index2)); } } return minDis; } } |
No comments:
Post a Comment