public class WordDistance {
private HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
public WordDistance(String[] words) {
for (int i = 0; i < words.length; i++) {
List<Integer> list = map.containsKey(words[i]) ? map.get(words[i]) : new ArrayList<Integer>();
list.add(i);
map.put(words[i], list);
}
}
public int shortest(String word1, String word2) {
List<Integer> list1 = map.get(word1);
List<Integer> list2 = map.get(word2);
int result = Integer.MAX_VALUE;
int p1 = 0;
int p2 = 0;
int size1 = list1.size();
int size2 = list2.size();
while (p1 < size1 && p2 < size2) {
result = Math.min(result, Math.abs(list1.get(p1) - list2.get(p2)));
if (list1.get(p1) > list2.get(p2)) {
p2 ++;
} else {
p1 ++;
}
}
return result;
}
}
// Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance = new WordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");