[leetcode]030-Substring with Concatenation of All Words[数学逻辑map]

本文深入解析 LeetCode 上一道难题:如何寻找一个字符串中包含所有给定单词串联而成的子串。文章详细介绍了算法思路,通过遍历和匹配单词,实现高效查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 原题

https://leetcode.com/problems/substring-with-concatenation-of-all-words/

2. 思路

题意:给出一个字符串,多个等长的单词,输出匹配时的索引下标。

给出的所有单词任意组合且中间无多余字符即匹配。

注意,字符串长度可能小于单词长度。

思路:题目较难。

由于单词等长,所以只需遍历词长这么多次。

每次遍历时,逐个判断取出的n个字符是否为给定的单词,同时累计单词个数。

3. 源码

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> res;
        if (words.empty() || s.empty()) //边界条件
            return res;
        
        map<string, int> mp1, mp2; //mp1存储已知的映射
        for(string word : words)
            ++mp1[word];
        int cnt = 0, left;
        int len = words[0].size();
        int num = words.size();
        if (s.size() < len) //边界
            return res;
        
        for (int i = 0; i < len; i++) //遍历len次即可
        {
            left = i;
            mp2.clear();
            cnt = 0;
            for (int j = i; j <= s.size()-len; j+=len)
            {
                string str = s.substr(j, len);
                if (mp1.count(str) > 0)
                {
                    ++mp2[str];
                    cnt++;
                    if (mp2[str] > mp1[str]) //单词多了,需要剔除一个
                    {
                        string ss;
                        do //从左开始逐个剔除多余的
                        {
                            ss = s.substr(left, len);
                            left += len;
                            --mp2[ss];
                            cnt--;
                        }
                        while (ss != str);
                    }
                }
                else //遇到不符合的单词,直接重新判断
                {
                    mp2.clear();
                    left = j+len;
                    cnt = 0;
                }
                
                if (cnt == num)
                {
                    res.push_back(left);
                    --mp2[s.substr(left, len)];
                    cnt--;
                    left += len; //向右滑动一个词长
                }
            }
        }
        
        return res;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值