forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
30 lines (27 loc) · 880 Bytes
/
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
class WordDistance {
private Map<String, List<Integer>> d = new HashMap<>();
public WordDistance(String[] wordsDict) {
for (int i = 0; i < wordsDict.length; ++i) {
d.computeIfAbsent(wordsDict[i], k -> new ArrayList<>()).add(i);
}
}
public int shortest(String word1, String word2) {
List<Integer> a = d.get(word1), b = d.get(word2);
int ans = 0x3f3f3f3f;
int i = 0, j = 0;
while (i < a.size() && j < b.size()) {
ans = Math.min(ans, Math.abs(a.get(i) - b.get(j)));
if (a.get(i) <= b.get(j)) {
++i;
} else {
++j;
}
}
return ans;
}
}
/**
* Your WordDistance object will be instantiated and called as such:
* WordDistance obj = new WordDistance(wordsDict);
* int param_1 = obj.shortest(word1,word2);
*/