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

相关推荐
AvocadoZeroOneOI14 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
文丑颜不良啊14 小时前
LeetCode3421~3440题目解析
java·leetcode
cjz389916 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
橘子1319 小时前
【高级数据库】关系代数基本概念
算法
电科_银尘1 天前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法
郝学胜-神的一滴1 天前
Effective STL 条款03:容器中的对象复制要廉价且正确
开发语言·数据结构·c++·算法·rpc·stl
秋天的怀念_David1 天前
算法一千零一夜 · 第三十三夜 · 跳表
java·程序人生·算法
LK_072 天前
【力扣】142. 环形链表 II |Python
python·leetcode·链表
Pniubi2 天前
力扣21合并两个有序链表
算法·leetcode·职场和发展
AIgorithmGEEK2 天前
std::unordered_map 与 std::unordered_set:接口、算法技巧与权衡 (速查)
c++·算法·哈希表·负载因子·桶·unordered_map·unordered_set