244. Shortest Word Distance II

This is a follow up of Shortest 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”].

Given word1 = “coding”, word2 = “practice”, return 3.
Given word1 = “makes”, word2 = “coding”, return 1.

Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

解法1:

先用hashmap没有疑问,之后在map中寻找最近的一对pair的时候可以用O(m+n)的复杂度解决,诀窍就是two pointers
按照大小顺序移动两个pointer

C++

1

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public class WordDistance {
HashMap<String, List<Integer>> map = null;
public WordDistance(String[] words) {
map = new HashMap<String, List<Integer>>();
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (!map.containsKey(word)) {
map.put(word, new ArrayList<Integer>());
}
map.get(word).add(i);
}
}
public int shortest(String word1, String word2) {
List<Integer> index1 = map.get(word1);
List<Integer> index2 = map.get(word2);
int res = Integer.MAX_VALUE;
int i = 0, j = 0;
while (i < index1.size() && j < index2.size()) {
int ii = index1.get(i);
int jj = index2.get(j);
res = Math.min(res, Math.abs(jj - ii));
if (ii < jj) {
i++;
} else {
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);
*/