leetcode 30. 串联所有单词的子串

思路

滑动窗口
将字符串s分为多个长度的w(每个单词长度)的子区间,
使用hash保存words中每个单词的个数
再开一个hash保存遍历时的每个单词
用cnt来记录子串中合法的单词个数
每次遍历,和m*w之前的那个单词比较,如果单词在第一个开的hash中,就减去那个单词
判断新的单词是不是保存在hash里且不超过words中的那个单词的个数,如果是,代表这个单词为合法单词,cnt+1,
当cnt和m(words.size)相等时,即为一组结果,将j-(m-1)*w存入结果集

class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> res;
        if(words.empty()) return res;
        int n = s.size(), m = words.size(), w = words[0].size();
        unordered_map<string,int> tot;
        for(auto& word:words) tot[word]++;
        for(int i = 0; i < w; i++){
            unordered_map<string,int> wd;
            int cnt = 0;
            for(int j = i;j + w <= n;j+=w){
                if(j >= i + w * m){
                    string word = s.substr(j - m * w, w);
                    wd[word]--;
                    if(wd[word]<tot[word])cnt--;
                }
                string word = s.substr(j,w);
                wd[word]++;
                if(wd[word] <= tot[word]) cnt++;
                if(cnt == m) res.push_back(j-(m-1)*w);
            }
        }
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值