forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortestWordDistance.java
More file actions
20 lines (19 loc) · 602 Bytes
/
ShortestWordDistance.java
File metadata and controls
20 lines (19 loc) · 602 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class ShortestWordDistance {
// 耗时3ms
public int shortestDistance(String[] words, String word1, String word2) {
int l1 = -1, l2 = -1, shortest = Integer.MAX_VALUE;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
l1 = i;
} else if (words[i].equals(word2)) {
l2 = i;
} else {
continue;
}
if (l1 >= 0 && l2 >= 0) {
shortest = Math.min(shortest, Math.abs(l1 - l2));
}
}
return shortest;
}
}