leetcode题解-438. Find All Anagrams in a String

本文介绍了一种寻找给定字符串中所有指定长度子串作为字母异位词的有效算法,并提供了详细的实现代码。

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

题目:Given a string s and a non-empty string p, find all the start indices of p’s anagrams in s.
Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100.The order of output does not matter.
示例:Input: s: “cbaebabacd” p: “abc” Output: [0, 6]
Explanation:
The substring with start index = 0 is “cba”, which is an anagram of “abc”.
The substring with start index = 6 is “bac”, which is an anagram of “abc”.

思路:题目的关键是判断s的一个字串是否为p的anagrams。之前有道题就是起到这个作用,有兴趣的同学可以去看看。这里仍适用该思路进行判断。代码如下所示:

    public static List<Integer> findAnagrams(String s, String p) {
        List<Integer> list = new ArrayList<Integer>();
        if(s == null || p == null || s.length() < p.length())   return list;
        int lengthp = p.length();
        int lengths = s.length();
        int[] hash = new int[26];
        //将字符串p的信息保存在hash数组中
        for(char c : p.toCharArray()){
            ++hash[c - 'a'];
        }
        int left = 0, right = 0;
        while(right < lengths){
            //如果s中right处的字符在p中,则将hash数组中相应计数减一。且如果该数字大于0说明仍然属于p的anagrams范畴。将lengthp--。
            if(hash[s.charAt(right++) - 'a']-- > 0) lengthp--;
            //当lengthp==0时表明left-right中的子串属于p的anagrams,记录该索引位置
            if(lengthp == 0)    list.add(left);
            //当发现一个anagrams后,再将其信息录入到hash数组中。即相当于将p的数据再次保存。且将lengthp也恢复原来的大小
            if(right - left == p.length() && hash[s.charAt(left++) - 'a']++ >= 0)    lengthp++;
        }
        //最终返回list即可
        return list;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值