Leecode 30. 串联所有单词的子串 滑动窗口+hash

原题链接:30. 串联所有单词的子串
在这里插入图片描述在这里插入图片描述
代码一:遍历,hash

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> res;
        int len=words[0].size();
        int l=len*int(words.size());
        if(s.size()<l || s.size()==0 ||words.size()==0)
           return res;
        unordered_map <string,int> m;
        for(auto w:words)
            m[w]++;
        for(int i=0;i<=s.size()-l;i++)
        {
            string tmp=s.substr(i,len);
            if(m[tmp]>0)
            {
                int pos=i;
                unordered_map <string,int> m1;
                while(m[tmp]+m1[tmp]>0)
                {
                    m1[tmp]--;
                    pos+=len;
                    tmp=s.substr(pos,len);
                }
                if(pos-i==l)
                    res.push_back(i);
            }
        }
        return res;
    }
};

下面的这个代码更快一点,参考题解:Leecode 串联所有单词的子串

Leecode 串联所有单词的子串 多解法

代码二:滑动窗口+hash

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> res;
        int len=words[0].size();
        int wl=len*int(words.size());
        if(s.size()<wl || s.size()==0 ||words.size()==0)
           return res;
        unordered_map <string,int> m;
        for(auto w:words)
            m[w]++;
        for(int i=0;i<len;i++)
        {
            int l=i,r=i,num=0;
            unordered_map <string,int> m1;
            while(r+len<=s.size())
            {
                string tmp=s.substr(r,len);
                r+=len;
                if(m.count(tmp)==0)
                {
                    num=0;l=r;m1.clear();
                }
                else 
                {
                    m1[tmp]++;num++;
                    while(m1[tmp]>m[tmp])
                    {
                        string t1=s.substr(l,len);
                        num--;
                        m1[t1]--;
                        l+=len;
                    }
                    if(num==words.size())
                        res.push_back(l);
                }
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值