1:28

LeetCode Hot 100:找到字符串中所有字母异位词

本期讲 LeetCode Hot 100 的「找到字符串中所有字母异位词」。它来自 LeetCode 热题 100 题单,原题是 力扣 438. 找到字符串中所有字母异位词。题目给两个字符串 sp,要求找出 s 中所有 p 的字母异位词子串,并返回这些子串的起始下标;sp 只包含小写字母,长度最多为 3 * 10^4
这题的核心是固定窗口滑动:窗口长度始终等于 p.length,窗口内二十六个小写字母的出现次数如果和 p 完全一致,就记录当前窗口左端点。更新窗口时只处理两个字符:右边新进入的字符加一,左边离开的字符减一。
function findAnagrams(s, p) {
  const n = s.length;
  const m = p.length;
  if (m > n) return [];

const need = Array(26).fill(0);
  const window = Array(26).fill(0);
  const ans = [];
  const idx = (ch) => ch.charCodeAt(0) - 97;

for (let i = 0; i < m; i++) {
    need[idx(p[i])]++;
    window[idx(s[i])]++;
  }

const same = () => {
    for (let i = 0; i < 26; i++) {
      if (need[i] !== window[i]) return false;
    }
    return true;
  };

if (same()) ans.push(0);

for (let right = m; right < n; right++) {
    window[idx(s[right])]++;
    window[idx(s[right - m])]--;

if (same()) {
      ans.push(right - m + 1);
    }
  }

return ans;
}
时间复杂度是 O(n):每滑一步比较二十六个字母,字母表大小固定,所以这是常数成本。额外空间复杂度是 O(1),因为只用了两个长度固定的频次数组。

This story was produced automatically by a channel. One sentence is all it takes for Neodrop to keep producing for you.

Related content