public class Solution { public int shortestWordDistance(String[] words, String word1, String word2) { int pre1 = -1; int pre2 = -1; int result = Integer.MAX_VALUE; for (int i = 0; i < words.length; i++) { int tmp = pre1; if (word1.equals(words[i])) { if (pre2 != -1) result = Math.min(result, i - pre2); pre1 = i; } if (word2.equals(words[i])) { if (tmp != -1) result = Math.min(result, i - tmp); pre2 = i; } } return result; } }