LeetCode 438. Find All Anagrams in a String

Given two strings s and p, return an array of all the start indices of p's anagrams in s. You may return the answer in any order.

Example 1:

复制代码
Input: s = "cbaebabacd", p = "abc"
Output: [0,6]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".

Example 2:

复制代码
Input: s = "abab", p = "ab"
Output: [0,1,2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".

Constraints:

  • 1 <= s.length, p.length <= 3 * 104
  • s and p consist of lowercase English letters.

就是要找p在s里有多少anagram,相当于是在一个字符串中找满足每个字母出现某个频率的substring(anagram -> frequency)。说是sliding window,但其实这个window的长度是固定的,也就是其实并不需要left和right,一个index遍历就行了。以及要找字母出现的频率,对于string来说可以直接用char\[\]来记录char - 'a'比用map方便多了。

代码写起来比较直观,几个自己遇到的坑:

  1. 刚开始脑子没想明白,while写了半天,数组边界搞的乱七八糟。改用for以后固定只看后边界,就清楚多了。

  2. 要考虑p.length() < s.length()的情况

    class Solution {
    public List findAnagrams(String s, String p) {
    List result = new ArrayList<>();
    int[] pChars = new int[26];
    int[] sChars = new int[26];
    if (s.length() < p.length()) {
    return result;
    }
    for (int i = 0; i < p.length(); i++) {
    pChars[p.charAt(i) - 'a']++;
    sChars[s.charAt(i) - 'a']++;
    }
    if (Arrays.equals(pChars, sChars)) {
    result.add(0);
    }

    复制代码
         for (int i = p.length(); i < s.length(); i++) {
             // remove first element in window
             sChars[s.charAt(i - p.length()) - 'a']--;
             // move window to the next
             sChars[s.charAt(i) - 'a']++;
             // update result
             if (Arrays.equals(pChars, sChars)) {
                 result.add(i - p.length() + 1);
             }
         }
    
         return result;
     }

    }

相关推荐
hanlin038 小时前
刷题笔记:力扣第32题-最长有效括号
笔记·算法·leetcode
All for pursuit.8 小时前
【动态规划-21】312.戳气球
数据结构·c++·算法·leetcode·动态规划
碧海银沙音频科技研究院10 小时前
基于炬芯ATS3089X自研AEC声学回声消除算法
算法
通问AI11 小时前
在两台 Mac Studio 上跑 800B 模型:MLX + RDMA over Thunderbolt 实测与四道门选型法
算法
ZywOo62311 小时前
《算法竞赛进阶指南》0x03 前缀和与差分
算法
Scintilla_y11 小时前
DAY2 滑动窗口
算法·leetcode·散列表
lvwangshu11 小时前
笛卡尔树
算法·图论
026d2311 小时前
状态信号只知“其然”不知“其所以然”:变工况机械故障诊断的物理盲区
算法
姜鱼问生12 小时前
备份和服务器在同一台机器上,等于没备份
算法·架构
姜鱼问生12 小时前
别再 chmod 777 了,用 ACL 给它开一扇窗
后端·算法·架构