单词距离

此博客链接:

单词距离

题目链接:https://leetcode-cn.com/problems/find-closest-lcci/

题目

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

示例:

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

words.length <= 100000
通过次数12,193提交次数17,768

题解

使用双指针思想,一个指针在前面,一个指针在后面,每次指针移动时,都判断是否是给定的单词,如果是给定的单词,则把前面一个指针放到后面一个指针上,并且把后面一个指针继续向后移动,如果两个指针中对应的值不相等,则记录两个指针对应的下标差值,然后把前面指针指向后面的指针,后面指针继续向后面移动,当两个指针值不同时,再次求两个只指针的差值并且和前面的差值比较,取差值小的值,继续上述操作,直到遍历到数组的最后。

代码

class Solution {
    public int findClosest(String[] words, String word1, String word2) {
        int i = 0;
        int j = 0;
        int min_distance = words.length+1;
        int count = 0;
        while ( j<words.length){
            //
            if ( words[j].equals(word1) || words[j].equals(word2)){
            count += 1; 
            if (!words[j].equals(words[i]) && count != 1){
                min_distance =  j-i < min_distance?j-i:min_distance;
            }
                i = j;
            }
            j++;
        }
        return min_distance;
    }
}

 

结果

 

posted @ 2021-05-23 22:57  萍2樱释  阅读(100)  评论(0编辑  收藏  举报