串联所有单词的子串

题目链接:

30. 串联所有单词的子串 - 力扣(LeetCode)

思路:

利用滑动窗口的思路去解决问题

因为题目提到需要满足的情况是串联子串,也就是说,某段字符串必须是同时出现所有的 word 数组,为了减少时间复杂度 ------ 我们利用滑动串口 在右边边界移动 word 单个单词的 位置来进行尽可能的匹配

所以 我们的外循环只需要循环 word 单个单词的长度即可(是在遍历每个位置的可能性)

我们利用滑动窗口,让右边界不停地在 map 里面记录我们所需的数量,直到所记录的单词数量超出,我们进行收缩左边界,直到满足条件,记录下来,其中我们会遇到有不匹配的单词(直接 清除 滑动窗口即可,因为不满足这个条件,也不会满足 串联子串 的定义)

代码:

javascript 复制代码
var findSubstring = function (s, words) {
    if (!s || !words || words.length === 0) return [];
    
    const wordLen = words[0].length;
    const wordCount = words.length;
    const sLen = s.length;
    const result = [];
    
    // 构建目标 Map
    const targetMap = new Map();
    for (const word of words) {
        targetMap.set(word, (targetMap.get(word) || 0) + 1);
    }
    
    // 分桶处理:只需要遍历 wordLen 次
    for (let i = 0; i < wordLen; i++) {
        let left = i;                          // 窗口左边界
        let right = i;                          // 窗口右边界
        let count = 0;                          // 当前窗口中匹配的单词数
        const currentMap = new Map();            // 当前窗口的单词频率
        
        // 滑动窗口
        while (right + wordLen <= sLen) {
            // 1. 右指针移动,加入新单词
            const rightWord = s.substring(right, right + wordLen);
            right += wordLen;
            
            if (targetMap.has(rightWord)) {
                // 更新当前窗口计数
                currentMap.set(rightWord, (currentMap.get(rightWord) || 0) + 1);
                count++;
                
                // 2. 如果某个单词超量,收缩左边界
                while (currentMap.get(rightWord) > targetMap.get(rightWord)) {
                    const leftWord = s.substring(left, left + wordLen);
                    currentMap.set(leftWord, currentMap.get(leftWord) - 1);
                    count--;
                    left += wordLen;
                }
                
                // 3. 如果匹配了所有单词,记录结果
                if (count === wordCount) {
                    result.push(left);
                    
                    // 4. 移动左边界,继续寻找下一个可能的位置
                    const leftWord = s.substring(left, left + wordLen);
                    currentMap.set(leftWord, currentMap.get(leftWord) - 1);
                    count--;
                    left += wordLen;
                }
            } else {
                // 遇到不匹配的单词,重置窗口
                currentMap.clear();
                count = 0;
                left = right;
            }
        }
    }
    
    return result;
};
相关推荐
像污秽一样2 小时前
算法设计与分析-习题5.4
数据结构·算法·排序算法
IronMurphy2 小时前
【算法二十四】101. 对称二叉树 543. 二叉树的直径
数据结构·算法·leetcode
qingy_20462 小时前
Java基础:数据类型
java·开发语言·算法
小璐资源网2 小时前
排序算法概览:十大排序算法一览
数据结构·算法·排序算法
Allen_LVyingbo2 小时前
PostgreSQL动态分区裁剪技术:查询性能优化解析(2026年版)
数据库·算法·观察者模式·postgresql·性能优化·架构
少许极端2 小时前
算法奇妙屋(三十二)-DFS解决floodfill问题
算法·深度优先·dfs·floodfill
m0_716667072 小时前
嵌入式C++驱动开发
开发语言·c++·算法
Lenyiin2 小时前
《LeetCode 顺序刷题》51 - 60
java·c++·python·算法·leetcode·深度优先·lenyiin
Sakinol#2 小时前
Leetcode Hot 100 —— 图论
算法·leetcode·图论