LeetCode 面试题 17.11. 单词距离

题目

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

示例:

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

提示:

words.length <= 100000

思路

双指针,遍历字符串数组,不断维护两个指针即可。

AC代码

点击查看代码
class Solution {
    public int findClosest(String[] words, String word1, String word2) {
        int index1 = -1;
        int index2 = -1;
        int ans = 100001;
        for(int i=0; i<words.length; i++) {
            String word = words[i];
            if( word.equals(word1) ) {
                index1 = i;
            }
            if( word.equals(word2) ) {
                index2 = i;
            }
            if( index1!=-1 && index2!=-1 ) {
                ans = Math.min(ans, Math.abs(index2-index1));
            }
        }
        return ans;
    }
}
posted @   Asimple  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示