[LeetCode]Shortest Word Distance
public class Solution { public int shortestDistance(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++) { String word = words[i]; if (word.equals(word1)) { if (pre2 != -1) { result = Math.min(i - pre2, result); } pre1 = i; } else if (word.equals(word2)) { if (pre1 != -1) { result = Math.min(i - pre1, result); } pre2 = i; } } return result; } }