LeetCode:找到字符串中的所有字母异位词

java 复制代码
class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();

        int sLen = s.length();
        int pLen = p.length();
        //s字符串的长度小于p字符串,直接没有
        if(sLen < pLen){
            return result;
        }

        int[] pCount = new int[26];
        int[] windowCount = new int[26];
        //构建p的图谱和s的前pLen的图谱
        for(int i = 0; i < pLen; i++){
            pCount[p.charAt(i) - 'a']++;
            windowCount[s.charAt(i) - 'a']++;
        }
        //先对前pLen个字符比较
        if(Arrays.equals(pCount,windowCount)){
            result.add(0);
        }
        //遍历pLen后面的字符
        for(int right = pLen; right < sLen; right++){
            int left = right - pLen;
            
            windowCount[s.charAt(right) - 'a']++;
            windowCount[s.charAt(left) - 'a']--;

            if(Arrays.equals(pCount,windowCount)){
                result.add(left + 1);
            }
        }
        return result;
    }
}

将初始化和循环分开写,减少if-else的使用

相关推荐
专注仿真5 分钟前
梯度提升类(XFBoost)算法详解与代码实例
开发语言·人工智能·python·算法·大模型训练·控制算法
小豆庄10 分钟前
视频遮罩追踪退场后ID撞号的排查—多目标场景下的失效
opencv·算法·bug·视频·python3.11
Tisfy42 分钟前
LeetCode 3882.网格图中最小异或路径:动态规划
算法·leetcode·动态规划
D e re k ZH2 小时前
P5025 [SNOI2017] 炸弹
c++·算法
A boy CDEF girl2 小时前
算法题专栏:优选算法
数据结构·算法·leetcode
没落之王2 小时前
三易五行看宋朝的三界确立
大数据·人工智能·算法
坤坤子吖2 小时前
算法学习——单调队列
开发语言·c++·笔记·学习·算法
Js.Tx4 小时前
【具体数学 Concrete Mathematics】2.1.5 一般性的方法
算法·具体数学
秋天的怀念_David5 小时前
算法一千零一夜 · 作品相关:版权与致谢声明
程序人生·算法·学习方法
揽星河..6 小时前
【C语言】数组
c语言·开发语言·算法