244. Shortest Word Distance II
Last updated
Last updated
class WordDistance {
private Map<String, List<Integer>> map = new HashMap<>();
public WordDistance(String[] wordsDict) {
for (int i = 0; i < wordsDict.length ; i++) {
String w = wordsDict[i];
List<Integer> data = map.getOrDefault(w, new ArrayList<>());
data.add(i);
map.put(w, data);
}
}
public int shortest(String word1, String word2) {
List<Integer> data1 = map.get(word1);
List<Integer> data2 = map.get(word2);
int i = 0, j = 0;
int min = Integer.MAX_VALUE;
while (i < data1.size() && j < data2.size()) {
min = Math.min(min, Math.abs(data1.get(i) - data2.get(j)));
if (data1.get(i) > data2.get(j)) {
j++;
} else {
i++;
}
}
return min;
}
}
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance obj = new WordDistance(wordsDict);
* int param_1 = obj.shortest(word1,word2);
*/