Description
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. Your method will be called repeatedly many times with different parameters.
Example:
Assume that words = [“practice”, “makes”, “perfect”, “coding”, “makes”].
Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = “makes”, word2 = “coding”
Output: 1
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
Solution
设计一个数据结构,能够传入一个String[], 然后查询任意两个单词在数组中的最近距离,单词可能在数组中重复出现。
I would use a hash map which contains a map from String to list of interger. The list of integer denotes the index of this word in the String array.
When search the shortest distance from two words. Get the two list then find the minimum distance using two for loops.
Code
class WordDistance {
private Map<String, List<Integer>> map = new HashMap<>();
public WordDistance(String[] words) {
for (int i = 0; i < words.length; i++){
if (map.containsKey(words[i])){
map.get(words[i]).add(i);
}
else{
List<Integer> list = new ArrayList<Integer>();
list.add(i);
map.put(words[i], list);
}
}
}
public int shortest(String word1, String word2) {
List<Integer> l1 = map.get(word1);
List<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);
*/
Time Complexity: O()
Space Complexity: O()
Review
Because we add the index of each word in sequence, it is actually a sorted list, so we could change shortest() to have better performance.
class WordDistance {
private Map<String, List<Integer>> map = new HashMap<>();
public WordDistance(String[] words) {
for (int i = 0; i < words.length; i++){
if (map.containsKey(words[i])){
map.get(words[i]).add(i);
}
else{
List<Integer> list = new ArrayList<Integer>();
list.add(i);
map.put(words[i], list);
}
}
}
public int shortest(String word1, String word2) {
List<Integer> l1 = map.get(word1);
List<Integer> l2 = map.get(word2);
int res = Integer.MAX_VALUE;
for (int i = 0, j = 0; i < l1.size() && j < l2.size(); ){
int index1 = l1.get(i);
int index2 = l2.get(j);
if (index1 < index2){
res = Math.min(res, index2 - index1);
i++;
}
else{
res = Math.min(res, index1 - index2);
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);
*/