This is afollow upofShortest Word Distance. The only difference is now you are given the list of words and your method will be called_repeatedly_many times with different parameters. How would you optimize it?
Design a class which receives a list of words in the constructor, and implements a method that takes two words_word1_and_word2_and return the shortest distance between these two words in the list.
For example,
Assume that words =["practice", "makes", "perfect", "coding", "makes"]
.
Givenword1=“coding”
,word2=“practice”
, return 3.
Givenword1="makes"
,word2="coding"
, return 1.
Note:
You may assume thatword1does not equal toword2, and_word1_and_word2_are both in the list.
class WordDistance {
Map<String, List<Integer>> hash;
public WordDistance(String[] words) {
hash = new HashMap<>();
for (int i = 0; i < words.length; i++){
if (hash.containsKey(words[i])){
hash.get(words[i]).add(i);
}
else{
List<Integer> list = new ArrayList<>();
list.add(i);
hash.put(words[i], list);
}
}
}
public int shortest(String word1, String word2) {
int ans = Integer.MAX_VALUE;
List<Integer> list1 = hash.get(word1);
List<Integer> list2 = hash.get(word2);
for (int i = 0, j = 0; i < list1.size() && j < list2.size(); ){
if (list1.get(i) < list2.get(j)){
ans = Math.min(ans, list2.get(j) - list1.get(i));
i++;
}
else{
ans = Math.min(ans, list1.get(i) - list2.get(j));
j++;
}
}
return ans;
}
}
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance obj = new WordDistance(words);
* int param_1 = obj.shortest(word1,word2);
*/