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

    }

相关推荐
加宝的起点雷达2 分钟前
40 条候选里 38 条来自同一个源,主卡整屏重样
人工智能·算法·创业
秋天的怀念_David9 分钟前
算法一千零一夜 · 第二十六夜 协议的母语
java·spring boot·算法
文丑颜不良啊1 小时前
LeetCode2021~2040题目解析
java·leetcode
闻缺陷则喜何志丹3 小时前
【C++特性】四种类型转
c++·算法·类型转换
喵本喵叁肆3 小时前
用 Boosting 把弱隐私算法炼成强隐私算法(英文原题:Boosting and Differential Privacy (FOCS 2010))
算法·集成学习·boosting
青梅味猪大肠4 小时前
【操作系统-60】临近适应算法
java·linux·开发语言·嵌入式硬件·算法·操作系统
其实防守也摸鱼18 小时前
个人学习 Pwn 思路:从基础到漏洞利用的进阶路径
大数据·前端·人工智能·chrome·算法·安全·网络安全
Nuanyt19 小时前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表