438. 找到字符串中所有字母异位词

104 阅读1分钟

题目

🔗题目链接:438. 找到字符串中所有字母异位词 - 力扣(LeetCode)

给定两个字符串 s 和 p,找到 s ****中所有 p ****的 异位词 的子串,返回这些子串的起始索引。不考虑答案输出的顺序。

异位词 指由相同字母重排列形成的字符串(包括相同的字符串)。

示例 1:

输入: s = "cbaebabacd", p = "abc"
输出: [0,6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的异位词。

示例 2:

输入: s = "abab", p = "ab"
输出: [0,1,2]
解释:
起始索引等于 0 的子串是 "ab", 它是 "ab" 的异位词。
起始索引等于 1 的子串是 "ba", 它是 "ab" 的异位词。
起始索引等于 2 的子串是 "ab", 它是 "ab" 的异位词。

提示:

  • 1 <= s.length, p.length <= 3 * 104
  • s 和 p 仅包含小写字母

思路

242. 有效的字母异位词的思路 + 滑动窗口

代码

function findAnagrams(s: string, p: string): number[] {
  const sLens = s.length;
  const pLens = p.length;

  if (sLens < pLens) return [];

  const answerArr: number[] = [];

  const baseCode = "a".charCodeAt(0);

  const sCount = new Array(26).fill(0);
  const pCount = new Array(26).fill(0);

  // 处理开始的元素
  for (let i = 0; i < pLens; ++i) {
    const sCountIndex = s.charCodeAt(i) - baseCode;
    sCount[sCountIndex]++;

    const pCountIndex = p.charCodeAt(i) - baseCode;
    pCount[pCountIndex]++;
  }

  if (sCount.toString() === pCount.toString()) {
    answerArr.push(0);
  }

  for (let i = 0; i < sLens - pLens; ++i) {
    // 删除窗口左边界记录的值
    const preIndex = s.charCodeAt(i) - baseCode;
    sCount[preIndex]--;
    
    // 记录窗口的右边界
    const currentIndex = s.charCodeAt(i + pLens) - baseCode;
    sCount[currentIndex]++;

    if (sCount.toString() === pCount.toString()) {
      answerArr.push(i + 1);
    }
  }

  return answerArr;
}