5.17号刷题

第一题 243 Shortest Word Distance

算法

分别记录下两个index的值,不断向前滚动。求最小值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class shortestDistance243 {
public int shortestDistance(String[] words, String word1, String word2) {
int word1_index = Integer.MAX_VALUE, word2_index = Integer.MAX_VALUE, distance = Integer.MAX_VALUE;;
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (word.equals(word1)) {
word1_index = i;
distance = Math.min(Math.abs(word1_index - word2_index), distance);
}
if (word.equals(word2)) {
word2_index = i;
distance = Math.min(Math.abs(word1_index - word2_index), distance);
}
}
return distance;
}
}