-
-
Notifications
You must be signed in to change notification settings - Fork 8.8k
/
Copy pathSolution.java
28 lines (28 loc) · 906 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
class Solution {
public int shortestWordDistance(String[] wordsDict, String word1, String word2) {
int ans = wordsDict.length;
if (word1.equals(word2)) {
for (int i = 0, j = -1; i < wordsDict.length; ++i) {
if (wordsDict[i].equals(word1)) {
if (j != -1) {
ans = Math.min(ans, i - j);
}
j = i;
}
}
} else {
for (int k = 0, i = -1, j = -1; k < wordsDict.length; ++k) {
if (wordsDict[k].equals(word1)) {
i = k;
}
if (wordsDict[k].equals(word2)) {
j = k;
}
if (i != -1 && j != -1) {
ans = Math.min(ans, Math.abs(i - j));
}
}
}
return ans;
}
}