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

    }

相关推荐
AllData公司负责人4 小时前
实战二:AllData大模型与AI数据底座-数据传输平台-DBSyncer,搭建 Http 接口同步至 Doris,API 业务数据自动拉取入数仓
大数据·数据库·数据仓库·人工智能·算法·http·doris
武子康5 小时前
火系被选七成,就应该削弱吗?
人工智能·算法·机器学习
夜不会漫长6 小时前
C++:C++11特性
开发语言·c++·算法
秋天的怀念_David6 小时前
算法一千零一夜 · 第三十七夜 · 类型的过路费
java·程序人生·算法
xckkcxxck8 小时前
Kaggle S6E10 冠军方案精读(二):245 个模型的合唱团,和一个只会“线性指挥“的老师
算法
饮水桶_T9 小时前
Git笔记
开发语言·笔记·算法
指掀涛澜天下惊9 小时前
强化学习进阶篇十四 DPO算法
深度学习·算法·机器学习·sft·预训练·dpo
AAA修煤气灶刘哥11 小时前
我都切到下一张图了,Agent 怎么还在解释上一张?
人工智能·算法·架构
Navigator_Z11 小时前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode
青少儿编程课堂13 小时前
蓝桥杯青少组图形化真题:校园无人机编队灯光秀解析(全国青少年信息素养大赛·电子学会12月图形化考级同源考点)
c++·python·算法·bfs·信息学竞赛