Skip to content

Commit e8f3c92

Browse files
authored
Create 243. Shortest Word Distance.java
1 parent 9bebaa6 commit e8f3c92

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

243. Shortest Word Distance.java

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
public class Solution {
2+
public int shortestDistance(String[] words, String word1, String word2) {
3+
int w1 = -1;
4+
int w2 = -1;
5+
int dist = Integer.MAX_VALUE;
6+
7+
for (int i = 0; i < words.length; i++) {
8+
if (words[i].equals(word1)) {
9+
w1 = i;
10+
}
11+
if (words[i].equals(word2)) {
12+
w2 = i;
13+
}
14+
if ((w1 != -1 && w2 != -1) && Math.abs(w1 - w2) < dist) {
15+
dist = Math.abs(w1 - w2);
16+
}
17+
}
18+
19+
return dist;
20+
}
21+
}

0 commit comments

Comments
 (0)