题目描述
有个内含单词的超大文本文件,给定任意两个不同的单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。
示例
示例 1:
输入:words = [“I”,“am”,“a”,“student”,“from”,“a”,“university”,“in”,“a”,“city”], word1 = “a”, word2 = “student”
输出:1
解题过程
思路及步骤
(1)总体上采用一次查询多次记录的方法;
(2)遍历循环数组,找到两个单次的出现位置,如果多次出现则多次记录;
(3)计算每一组两个单次之间的距离,取距离最小的即可
代码展示
public class FindClosest {
public static int findClosest(String[] words, String word1, String word2) {
int length = words.length;
int first = 0 - length;
int second = length;
int minDistance = length;
for (int i = 0; i < length; i++) {
if (words[i].equals(word1)) {
first = i;
}
if (words[i].equals(word2)) {
second = i;
}
minDistance = Math.min(minDistance, Math.abs(second - first));
}
return minDistance;
}
public static void main(String[] args) {
String string = "I am a student";
String[] words = string.split(",");
String word1 = "I";
String word2 = "a";
int result = findClosest(words, word1, word2);
System.out.println(result);
}
}
168

被折叠的 条评论
为什么被折叠?



