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

    }

相关推荐
倒头就睡的小比特4 天前
算法竞赛C++常用的STL
c++·算法
小羊没烦恼!4 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼4 天前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
旖旎夜光4 天前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark4 天前
大规模并行计算中的负载均衡算法研究4
算法
Because_of_Her14 天前
并查集-听课笔记
笔记·算法·并查集
码流子4 天前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构
another heaven4 天前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
wzdark4 天前
从算法设计模式看编程思维的抽象能力4
算法
2601_962218614 天前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法