Skip to content

Commit 35f6535

Browse files
authored
Create 244. Shortest Word Distance II.java
1 parent e8f3c92 commit 35f6535

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

244. Shortest Word Distance II.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
public class WordDistance {
2+
HashMap<String, ArrayList<Integer>> map;
3+
4+
public WordDistance(String[] words) {
5+
map = new HashMap<>();
6+
7+
for (int i = 0; i < words.length; i++) {
8+
ArrayList<Integer> a;
9+
if (map.containsKey(words[i])) {
10+
a = map.get(words[i]);
11+
} else {
12+
a = new ArrayList<>();
13+
}
14+
a.add(i);
15+
map.put(words[i], a);
16+
}
17+
}
18+
19+
// Important to optimize this for O(n) instead of O(n^2) where n is the avg list length
20+
public int shortest(String word1, String word2) {
21+
ArrayList<Integer> w1 = map.get(word1);
22+
ArrayList<Integer> w2 = map.get(word2);
23+
24+
int dist = Integer.MAX_VALUE;
25+
26+
for (int i = 0, j = 0; i < w1.size() && j < w2.size(); ) {
27+
int index1 = w1.get(i);
28+
int index2 = w2.get(j);
29+
30+
if (index1 < index2) {
31+
dist = Math.min(dist, index2 - index1);
32+
i++;
33+
} else {
34+
dist = Math.min(dist, index1 - index2);
35+
j++;
36+
}
37+
}
38+
39+
return dist;
40+
}
41+
}
42+
43+
/**
44+
* Your WordDistance object will be instantiated and called as such:
45+
* WordDistance obj = new WordDistance(words);
46+
* int param_1 = obj.shortest(word1,word2);
47+
*/

0 commit comments

Comments
 (0)