LeetCode Hot100 438.找到字符串中所有字母异位词

题目

给定两个字符串 sp,找到 s中所有 p异位词的子串,返回这些子串的起始索引。不考虑答案输出的顺序。

异位词指由相同字母重排列形成的字符串(包括相同的字符串)。

代码

java 复制代码
class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        int n = s.length(), m = p.length();
        List<Integer> res = new ArrayList<>();
        if (n < m)
            return res;
        int[] pCnt = new int[26];
        int[] sCnt = new int[26];
        for (int i = 0; i < m; i++) {
            pCnt[p.charAt(i) - 'a']++;
            sCnt[s.charAt(i) - 'a']++;
        }
        if (Arrays.equals(sCnt, pCnt)) {
            res.add(0);
        }
        for (int i = m; i < n; i++) {
            sCnt[s.charAt(i - m) - 'a']--;
            sCnt[s.charAt(i) - 'a']++;
            if(Arrays.equals(sCnt, pCnt)){
                res.add(i - m + 1);
            }
        }
        return res;
    }
}
相关推荐
Swift社区10 分钟前
Swift 解法详解:LeetCode 371《两整数之和》
开发语言·leetcode·swift
Swift社区11 分钟前
Swift 解法详解 LeetCode 362:敲击计数器,让数据统计更高效
开发语言·leetcode·swift
Q741_14721 分钟前
C++ 前缀和 高频笔试考点 实用技巧 牛客 DP34 [模板] 前缀和 题解 每日一题
开发语言·c++·算法·前缀和·牛客网
RTC老炮1 小时前
webrtc弱网-LossBasedBandwidthEstimation类源码分析与算法原理
网络·算法·webrtc
豆浩宇2 小时前
Conda环境隔离和PyCharm配置,完美同时运行PaddlePaddle和PyTorch
人工智能·pytorch·算法·计算机视觉·pycharm·conda·paddlepaddle
一只鱼^_2 小时前
牛客周赛 Round 108
数据结构·c++·算法·动态规划·图论·广度优先·推荐算法
小刘的AI小站3 小时前
leetcode hot100 二叉搜索树
算法·leetcode
自信的小螺丝钉3 小时前
Leetcode 876. 链表的中间结点 快慢指针
算法·leetcode·链表·指针
红豆怪怪3 小时前
[LeetCode 热题 100] 32. 最长有效括号
数据结构·python·算法·leetcode·动态规划·代理模式
参.商.3 小时前
【Day21】146.LRU缓存 (Least Recently Used)
leetcode·缓存·golang