滑动窗口刷题(四)困难

目录

串联所有单词的子串

1.题目解析

2.算法思路

3.代码编写




1.题目解析

例:如果 s = "barfoothefoobarman" word = ["foo","bar"]

那么就去s中寻找"foobar"或者"barfoo",返回找到字串的起始位置。

s = "barfoofoobarthefoobarman" word = ["bar","foo","the"]

那么就去s中寻找"barfoothe","barthefoo","foobarthe","foothebar","thef7oobar","thebarfoo".

2.算法思路

哈希表+滑动窗口

哈希表部分

定义hash1存储word中的字符串。

定义两个维护窗口的指针left,right。

定义hash2存储s中的字符串。

滑动窗口部分

进窗口:将长度为word[0].size()的字符存入hash2

判断:看窗口的长度,是否大于寻找字串的长度

出窗口:将长度为word[0].size()的字符从hash2中删除

3.代码编写

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        unordered_map<string,int> map1;
        for(string &str : words){
            map1[str]++;
        } 
        vector <int>ans;
        int len = words[0].size();//单词长度
        int n = words.size();//
        if(len > s.size())
        {
            return {};
        }

        for(int i = 0; i < len; i++)
        {
            int count = 0;
            unordered_map<string,int> map2;//存储字符串s
            for(int left = i, right = i; right <= s.size()-len; right += len)
            {
                string in = s.substr(right,len);//进窗口
                if(++map2[in] <= map1[in])
                    count++;

                if((right-left+1) > n*len && left < right)//判断1
                {
                    string out = s.substr(left,len);
                    if(map2[out]-- <= map1[out])//出窗口
                    {
                        count--;
                    }
                    left += len;
                }
                if(count == n)
                {
                    ans.push_back(left);
                }
            }

        }

        return ans;
    }
};

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值