面试经典题---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;
    }
};
相关推荐
tyb3333332 分钟前
leetcode:吃苹果和队列
算法·leetcode·职场和发展
多恩Stone7 分钟前
【3D-AICG 系列-15】Trellis 2 的 O-voxel Shape: Flexible Dual Grid 代码与论文对应
人工智能·python·算法·3d·aigc
weixin_448119947 分钟前
Datawhale 大模型算法全栈基础篇 202602第4次笔记
笔记·算法
网小鱼的学习笔记8 分钟前
leetcode876:链表的中间结点
数据结构·链表
sali-tec8 分钟前
C# 基于OpenCv的视觉工作流-章27-图像分割
图像处理·人工智能·opencv·算法·计算机视觉
NEXT0622 分钟前
React 核心揭秘:虚拟 DOM 原理与 Diff 算法深度解析
前端·react.js·面试
踩坑记录32 分钟前
leetcode hot100 74. 搜索二维矩阵 二分查找 medium
leetcode
TracyCoder12332 分钟前
LeetCode Hot100(60/100)——55. 跳跃游戏
算法·leetcode
宵时待雨33 分钟前
C++笔记归纳2:类和对象
c++·笔记
李云龙炮击平安线程38 分钟前
Python中的接口、抽象基类和协议
开发语言·后端·python·面试·跳槽