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的使用

相关推荐
To_OC4 小时前
LC 131 分割回文串:刚学回溯时,我连怎么切字符串都想不明白
javascript·算法·leetcode
旖-旎5 小时前
LeetCode 518:零钱兑换||(完全背包)—— 题解
c++·算法·leetcode·动态规划·背包问题
To_OC6 小时前
LC 42 接雨水:暴力超时卡半天?前后缀数组一用就通了
javascript·算法·leetcode
delishcomcn7 小时前
AI视觉识别+分切算法:电化铝缺陷检测与裁切一体化解锁
人工智能·算法
触底反弹7 小时前
深入理解大模型采样:Temperature、Top-K、Top-P 的原理与实战
人工智能·算法·面试
雪碧聊技术7 小时前
力扣 LCR 091. 粉刷房子 —— 动态规划入门详解
算法·动态规划
CV-Climber10 小时前
检索技术的实际应用
人工智能·算法
hhzz11 小时前
Tiger AI Platform平台中增加人脸识别功能
图像处理·人工智能·算法·计算机视觉·大模型
从零开始的代码生活_11 小时前
C++ 继承详解:访问控制、对象模型、菱形继承与设计取舍
开发语言·c++·后端·学习·算法