【滑动窗口】438. 找到字符串中所有字母异位词

本文介绍如何使用Python通过双指针和位图技术解决给定字符串s中的子串与目标字符串p的异位词查找问题,提供示例和详细代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

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

示例 1:

输入: s = "cbaebabacd", p = "abc"
输出: [0,6]
解释:
起始索引等于 0 的子串是 "cba", 它是 "abc" 的异位词。
起始索引等于 6 的子串是 "bac", 它是 "abc" 的异位词。

示例 2:

输入: s = "abab", p = "ab"
输出: [0,1,2]
解释:
起始索引等于 0 的子串是 "ab", 它是 "ab" 的异位词。
起始索引等于 1 的子串是 "ba", 它是 "ab" 的异位词。
起始索引等于 2 的子串是 "ab", 它是 "ab" 的异位词。

提示:

1 <= s.length, p.length <= 3 * 104
s 和 p 仅包含小写字母

题解:

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        // 使用双指针+位图
        int n = s.length();
        int m = p.length();
        // 
        if (m > n) {
            return new ArrayList<>();
        }
        // p 在位图中的位置
        int[] needs = new int[26];
        for (int i=0;i<m;i++) {
            needs[p.charAt(i) - 'a']++;
        }
        // 使用窗口滑动 s
        int start = 0;
        int end = 0;
        int[] matched = new int[26]; // 窗口
        // 先比较前m个字符
        while (end < m) {
            matched[s.charAt(end)-'a']++;
            end++;
        }
        if (same(needs, matched)) {
            result.add(start);
        }
        while (start<n && end<n) {
            // 滑动窗口
            matched[s.charAt(start)-'a']--;
            matched[s.charAt(end)-'a']++;
            start++;
            end++;
            if (same(needs, matched)) {
                result.add(start);
            }
        }
        return result;
    }

    public boolean same(int[] needs, int[] matched) {
        for (int i=0;i<needs.length;i++) {
            if (needs[i] != matched[i]) {
                return false;
            }
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值