面试经典题---30.串联所有单词的子串

30.串联所有单词的子串

我的解法:

滑动窗口:

  • 解法中用到了两个哈希表map1和map2,分别用于记录words中各个单词的出现频数和当前滑动窗口[left, right)中单词的出现频数;
  • 外部for循环i从0到len - 1,内部while循环每次会让滑动窗口滑动len步,即开头位置为i时,这一轮就可以遍历到i + k*len开头的子串,因此i取0到len - 1可以覆盖所有的子串开头情况;
  • 内部while循环每次先取right开头的长度为len的子串tmp,判断tmp是否是words中的单词:
    • 不是则更新窗口左端点,清空count和哈希表map2
    • 属于words中的单词时count加1,更新哈希表map2,若tmp重复出现了,则要收缩滑动窗口左端,并更新count和map2(注意判断重复出现这里用的是while循环)
cpp 复制代码
class Solution {
public:
    vector<int> findSubstring(string s, vector<string>& words) {
        vector<int> res;
        if(s.empty() || words.empty()){
            return res;
        }
        int len = words[0].size();
        int size = words.size();
        unordered_map<string, int> map1;
        for(auto w : words){
            map1[w]++;
        }
        for(int i = 0; i < len; ++i){
            int left = i, right = i;
            int count = 0;
            unordered_map<string,int> map2;
            while(right + len <= s.size()){
                string tmp = s.substr(right, len);
                right += len;
                if(map1.count(tmp) == 0){
                    left = right;
                    count = 0;
                    map2.clear();
                }
                else{
                    count++;
                    map2[tmp]++;
                    while(map1[tmp] < map2[tmp]){
                        string re_word = s.substr(left, len);
                        count--;
                        map2[re_word]--;
                        left += len;
                    }
                    if(count == size){
                        res.push_back(left);
                    }
                }
            }
        }
        return res;
    }
};
相关推荐
sheeta19981 小时前
LeetCode 每日一题笔记 日期:2025.11.24 题目:1018. 可被5整除的二进制前缀
笔记·算法·leetcode
是小胡嘛4 小时前
C++之Any类的模拟实现
linux·开发语言·c++
Want5957 小时前
C/C++跳动的爱心①
c语言·开发语言·c++
lingggggaaaa7 小时前
免杀对抗——C2远控篇&C&C++&DLL注入&过内存核晶&镂空新增&白加黑链&签名程序劫持
c语言·c++·学习·安全·网络安全·免杀对抗
phdsky7 小时前
【设计模式】建造者模式
c++·设计模式·建造者模式
H_-H7 小时前
关于const应用与const中的c++陷阱
c++
coderxiaohan7 小时前
【C++】多态
开发语言·c++
gfdhy7 小时前
【c++】哈希算法深度解析:实现、核心作用与工业级应用
c语言·开发语言·c++·算法·密码学·哈希算法·哈希
Warren987 小时前
Python自动化测试全栈面试
服务器·网络·数据库·mysql·ubuntu·面试·职场和发展
百***06017 小时前
SpringMVC 请求参数接收
前端·javascript·算法