面试经典题---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;
    }
};
相关推荐
im_AMBER1 天前
Leetcode 126 两数之和 II - 输入有序数组 | 盛最多水的容器
数据结构·学习·算法·leetcode
lxl13071 天前
C++算法(5)位运算
java·c++·算法
tankeven1 天前
HJ96 表示数字
c++·算法
嵌入式×边缘AI:打怪升级日志1 天前
C语言算术赋值运算复习笔记
c语言·stm32·单片机·算法·51单片机·proteus·代码
lxl13071 天前
C++算法(4)前缀和
开发语言·c++·算法
君生我老1 天前
C++ 多态
c++
不想看见4041 天前
Minimum Path Sum 基本动态规划:二维--力扣101算法题解笔记
算法·leetcode·动态规划
啊阿狸不会拉杆1 天前
《计算机视觉:模型、学习和推理》第 7 章-复杂数据密度建模
人工智能·python·学习·算法·计算机视觉·t分布·复杂数据密度建模
NEXT061 天前
深拷贝与浅拷贝的区别
前端·javascript·面试
Loo国昌1 天前
【AI应用开发实战】00_StockPilotX技术博客专栏:从零构建生产级AI金融分析系统
人工智能·算法·语言模型·自然语言处理·金融·prompt