-
-
Notifications
You must be signed in to change notification settings - Fork 8.9k
/
Copy pathSolution.java
34 lines (31 loc) · 1.08 KB
/
Solution.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
class WordDistance {
private Map<String, List<Integer>> words;
public WordDistance(String[] wordsDict) {
words = new HashMap<>();
for (int i = 0; i < wordsDict.length; ++i) {
List<Integer> indexes = words.getOrDefault(wordsDict[i], new ArrayList<>());
indexes.add(i);
words.put(wordsDict[i], indexes);
}
}
public int shortest(String word1, String word2) {
List<Integer> idx1 = words.get(word1);
List<Integer> idx2 = words.get(word2);
int i1 = 0, i2 = 0, shortest = Integer.MAX_VALUE;
while (i1 < idx1.size() && i2 < idx2.size()) {
shortest = Math.min(shortest, Math.abs(idx1.get(i1) - idx2.get(i2)));
boolean smaller = idx1.get(i1) < idx2.get(i2);
if (smaller) {
++i1;
} else {
++i2;
}
}
return shortest;
}
}
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance obj = new WordDistance(wordsDict);
* int param_1 = obj.shortest(word1,word2);
*/