单词距离

有个内含单词的超大文本文件,给定任意两个不同的单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此优化吗?

  • 输入:words = [“I”,”am”,”a”,”student”,”from”,”a”,”university”,”in”,”a”,”city”], word1 = “a”, word2 = “student”
    输出:1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var findClosest = function(words, word1, word2) {
let [index1, index2] = [-1,-1];
let result = words.length;
for(let i = 0; i < words.length; i ++){
let word = words[i];
if(word === word1){
index1 = i;
}else if(word === word2){
index2 = i;
}
if(index1 > 0 && index2 > 0){
result = Math.min(result, Math.abs(index1 - index2));
}
}
return result;
};