面试经典题---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;
    }
};
相关推荐
草莓熊Lotso13 分钟前
【Linux网络】UDP Socket 编程全解析:从回显服务到通用字典服务,从零实现工业级代码
linux·运维·服务器·数据库·c++·单片机·udp
飞鸿踏雪(蓝屏选手)6 小时前
137 ≤ Chrome 主密钥获取研究
c++·chrome·windows·网络安全·逆向分析
洛水水6 小时前
【力扣100题】18.随机链表的复制
算法·leetcode·链表
南宫萧幕7 小时前
规则基 EMS 仿真实战:SOC 区间划分与 Simulink 闭环建模全解
算法·matlab·控制
爱滑雪的码农7 小时前
Java基础十七:数据结构
数据结构
多加点辣也没关系7 小时前
数据结构与算法|第二十三章:高级数据结构
数据结构·算法
孬甭_9 小时前
初识数据结构与算法
数据结构
hoiii1879 小时前
孤立森林 (Isolation Forest) 快速异常检测系统
算法
c++之路10 小时前
适配器模式(Adapter Pattern)
java·算法·适配器模式
吴声子夜歌11 小时前
Java——接口的细节
java·开发语言·算法