jd1711.单词距离

题目描述

有个内含单词的超大文本文件,给定任意两个单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。

示例:

1
2
输入:words = ["I","am","a","student","from","a","university","in","a","city"], word1 = "a", word2 = "student"
输出:1

题解

双指针

  1. 从前往后遍历字符串组
  2. 如果当前的字符串与word1相同, 更新当前索引index1; 如果当前的字符串与word2相同, 更新当前索引index2
  3. 若两个索引都不为初始值-1, 即都已成功定位, 则计算当前距离
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public int findClosest(String[] words, String word1, String word2) {
int len = words.length;
int index1 = -1;
int index2 = -1;
int min = Integer.MAX_VALUE;

for (int i = 0; i < len; i++) {
if (words[i].equals(word1)) {
index1 = i;
}
if (words[i].equals(word2)) {
index2 = i;
}

if (index1 != -1 && index2 != -1)
min = Math.min(min, Math.abs(index1 - index2));

}
return min;
}
-------------本文结束感谢您的阅读-------------
可以请我喝杯奶茶吗