Open yokostan opened 5 years ago
public class Solution { public int shortestWordDistance(String[] words, String word1, String word2) { int p1 = -1, p2 = -1, min = Integer.MAX_VALUE; int n = words.length; for(int i = 0; i < n; i++){ if(!word1.equals(word2)){ if(words[i].equals(word1)) p1 = i; if(words[i].equals(word2)) p2 = i; if(p1 != -1 && p2 != -1){ min = Math.min(min, Math.abs(p1 - p2)); } } else {//p1 is previous pointer, p2 is current pointer if(words[i].equals(word1)){ if(p1 != -1){ p2 = i; min = Math.min(min, Math.abs(p1 - p2)); int tmp = p2; p2 = p1; p1 = tmp; } else { p1 = i; } } } } return min; } }