class WordDistance {
public int res = Integer.MAX_VALUE;
public HashMap<String, ArrayList<Integer>> map = new HashMap<>();
public WordDistance(String[] words) {
for (int i = 0; i < words.length; i++) {
if (!map.containsKey(words[i])) {
map.put(words[i], new ArrayList<Integer>());
}
map.get(words[i]).add(i);
}
}
public int shortest(String word1, String word2) {
ArrayList<Integer> l1 = map.get(word1);
ArrayList<Integer> l2 = map.get(word2);
int res = Integer.MAX_VALUE;
for (int i = 0; i < l1.size(); i++) {
for (int j = 0; j < l2.size(); j++) {
res = Math.min(res, Math.abs(l1.get(i) - l2.get(j)));
}
}
return res;
}
}
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance obj = new WordDistance(words);
* int param_1 = obj.shortest(word1,word2);
*/
HashMap: