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

相关推荐
云泽8082 小时前
深入 AVL 树:原理剖析、旋转算法与性能评估
数据结构·c++·算法
Wilber的技术分享3 小时前
【LeetCode高频手撕题 2】面试中常见的手撕算法题(小红书)
笔记·算法·leetcode·面试
邪神与厨二病3 小时前
Problem L. ZZUPC
c++·数学·算法·前缀和
梯度下降中4 小时前
LoRA原理精讲
人工智能·算法·机器学习
IronMurphy4 小时前
【算法三十一】46. 全排列
算法·leetcode·职场和发展
czlczl200209254 小时前
力扣1911. 最大交替子序列和
算法·leetcode·动态规划
靴子学长5 小时前
Decoder only 架构下 - KV cache 的理解
pytorch·深度学习·算法·大模型·kv
寒秋花开曾相惜5 小时前
(学习笔记)3.8 指针运算(3.8.3 嵌套的数组& 3.8.4 定长数组)
java·开发语言·笔记·学习·算法
Гений.大天才5 小时前
2026年计算机领域的年度主题与范式转移
算法