244. Shortest Word Distance II
Shortest Word Distance II
Solution
public class WordDistance {
Map<String, List<Integer>> map;
public WordDistance(String[] words) {
map = new HashMap<>();
for(int i = 0; i < words.length; i ++) {
if (map.containsKey(words[i])) {
map.get(words[i]).add(i);
} else {
List<Integer> indices = new ArrayList<>();
indices.add(i);
map.put(words[i], indices);
}
}
}
public int shortest(String word1, String word2) {
List<Integer> indices1 = map.get(word1);
List<Integer> indices2 = map.get(word2);
int distance = Integer.MAX_VALUE;
for(int i : indices1) {
for(int j : indices2) {
distance = Math.min(distance, Math.abs(i-j));
}
}
return distance;
}
}
// Your WordDistance object will be instantiated and called as such:
// WordDistance wordDistance = new WordDistance(words);
// wordDistance.shortest("word1", "word2");
// wordDistance.shortest("anotherWord1", "anotherWord2");Last updated