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;
     }

    }

相关推荐
LB21121 小时前
力扣102 198 70 55
数据结构·算法·leetcode
鹿角片ljp1 小时前
LeetCode 42:接雨水|前后最大值DP
算法·leetcode·动态规划
北域码匠10 小时前
高通滤波算法深度解析(High-Pass Filter)
stm32·算法·c#·数字信号处理·嵌入式开发·滤波算法·高通滤波
指掀涛澜天下惊10 小时前
强化学习进阶篇八 策略梯度算法
深度学习·学习·算法·强化学习
乌萨奇也要立志学C++10 小时前
【洛谷】kmp算法
开发语言·算法
禹凕10 小时前
Dijkstra算法详解与应用
python·算法
YaraMemo11 小时前
元启发式算法框架
人工智能·算法·5g·信息与通信·启发式算法·信号处理
weixin_3077791311 小时前
一维无粘 Burgers 方程的激波形成问题:MacCormack 格式求解
c++·算法·matlab