LeetCode每日一题(2022/5/27)面试题 17.11. 单词距离(中等)

面试题 17.11. 单词距离icon-default.png?t=M4ADhttps://leetcode.cn/problems/find-closest-lcci/

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

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-closest-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


简单模拟即可

class Solution {
public:
    int findClosest(vector<string>& words, string word1, string word2) {
        int l  = words.size();
        int ans = l;
        int index1 = -1;
        int index2 = -1;
        for (int i = 0; i < l; i++)
        {
            if (word1 == words[i])
                index1 = i;
            else if (word2 == words[i])
                index2 = i;
            if (index1 >= 0 && index2 >= 0)
                ans = min(ans, abs(index1 - index2));
        }
        return ans;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值