串联所有单词的字串题解

博客讲述了如何使用滑动窗口算法解决寻找单词串联子串的问题。作者首先尝试了暴力解法,然后改进为正确的滑动窗口方法,提高了效率。讨论了时间复杂度从O(N^2)优化到O(mn),并提到一个更优的8ms解决方案待进一步分析。

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

串联所有单词的字串题解

有单词串联形成的子串的起始位置。

注意子串要与 words 中的单词完全匹配,中间不能有其他字符,但不需要考虑 words 中单词串联的顺序。
s = “barfoothefoobarman”,
words = [“foo”,“bar”]
输出:[0,9]

题解:
暴力就不考虑了,我第一种方法是,破产版的滑动窗口,每次滑动一个字符,用两个map<string,int>一个dict存words,一个tmp存当前滑动窗的单词。然后确定tmp的单词对应匹配数是否在dict可以找到,挨个由于words的单词长度都一样,我想直接每次跳length_words进行匹配,显然会丢结果。而且效果真的丢人。提交里空间和时间都是倒数5%。嘿嘿,把我都气笑了。
看了前面的代码,顿悟,滑动窗口的正确姿势。
滑动每次肯定是要按leng_word来滑动的,同时采用leng_word次外部循环确保不漏情况。为什么是leng_word次呢?既然是找子串,而且子串长度必然是leng_word的倍数,则外部循环只需按照leng_word的余数作为起始即可。
前者和后者时间复杂度分析分别是O(N2),O(mn)m=leng_word,后者避免了很多不必要的计算。
贴代码:

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int>res;
        unsigned int length=words.size();
        if(s.empty()||words.empty())return res;
        unsigned int ea_leng=words[0].size();
        if(!ea_leng)return res;
        unsigned int wins=ea_leng*length;
        
        unordered_map<string,int> dict;
        for (auto &a:words)++dict[a];
        
        if (s.size()<wins)
            return res;
        unsigned int s_leng=s.size();
        //滑动窗口思想
        unsigned int st,ed;
        st=0;ed=0;
        for(int i=0;i<ea_leng;i++)
        {
            unordered_map<string,int> temp;
            st=i;
            ed=st;
            while(ed+ea_leng<=s_leng)
            {
                string bs=s.substr(ed,ea_leng);
                ed+=ea_leng;
                if(dict.find(bs)==dict.end())
                {
                    st=ed;
                    temp.clear();
                }
                else
                {
                    ++temp[bs];
                    if(temp[bs]>dict[bs])
                    {
                        while(temp[bs]>dict[bs])
                        {
                            string buf=s.substr(st,ea_leng);
                            --temp[buf];
                            st+=ea_leng;
                        }
                    }
                    if(ed-st==wins)
                        res.push_back(st);
                }
            }
        }
        return res;
    }
};

第一名是8ms,而且方法很独特,明天看看,再另外分析。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值