1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public class Solution { public int shortestWordDistance(String[] words, String word1, String word2) { int index1 = -1; int index2 = -1; int minDis = Integer.MAX_VALUE; boolean same = word1.equals(word2); for (int i = 0; i < words.length; i++){ if (words[i].equals(word1)){ if (same && index1 != -1){ minDis = Math.min(minDis, Math.abs(index1-i)); } 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; } } |
Tuesday, November 17, 2015
[leetcode]Shortest Word Distance III
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment