Skip to content

30. 串联所有单词的子串 ​

  • 题号:30
  • 来源:LeetCode
  • 难度:困难
  • 标签:滑动窗口 哈希表 字符串
  • 语言:TypeScript
  • 解法:1 个
  • 作者:lmliheng
  • 最近更新:2026-09-27

TypeScript · O(n*m) 时间 · O(k) 空间 · 更新于 2026-09-27

按单词长度分组滑动窗口,比较计数表

typescript
/**
 * @difficulty hard
 * @tags 滑动窗口,哈希表,字符串
 * @time O(n*m)
 * @space O(k)
 * @note 按单词长度分组滑动窗口,比较计数表
 * @30. 串联所有单词的子串
 */

function findSubstring(s:string, words:string[]) {
    const res:number[] = [];
    if (!s || s.length === 0 || !words || words.length === 0) return res;

    const wordLen = words[0].length;
    const wordNum = words.length;
    const map = new Map();

    for (const word of words) {
        map.set(word, (map.get(word) || 0) + 1);
    }

    for (let i = 0; i < wordLen; i++) {
        let left = i, right = i, count = 0;
        const tmpMap = new Map();

        while (right + wordLen <= s.length) {
            const w = s.slice(right, right + wordLen);
            tmpMap.set(w, (tmpMap.get(w) || 0) + 1);
            right += wordLen;
            count++;
            while ((tmpMap.get(w) || 0) > (map.get(w) ?? 0)) {

                const tw = s.slice(left, left + wordLen);
                tmpMap.set(tw, tmpMap.get(tw) - 1);
                left += wordLen;
                count--;
            }

            if (count === wordNum) res.push(left);
        }
    }

    return res

};

源码:ts/leetcode/30. 串联所有单词的子串.ts


在 GitHub 上查看题目所在目录:lmliheng/algorithm