leetcode[438] Find All Anagrams in a String

本文介绍了一种利用窗口移动思想解决寻找字符串中所有字谜变换起始下标的算法实现,适用于长度不超过20100的小写英文字母组成的字符串。

摘要生成于 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.


题目大意:

给定一个字符串s与一个非空字符串p,寻找s中所有p的字谜变换的起始下标。

字符串只包含小写英文字母并且s和p的长度均不超过20100。

输出顺序无所谓。

这里采用窗口移动的思想

class Solution {
    public List<Integer> findAnagrams(String s, String t) {
       
//创建一个list作为result,用作返回值。
        List<Integer> result = new LinkedList<>();
        if(t.length()> s.length()) return result;
        
    //创建一个HashMap,来保存给定的比对字符集
    //key代表指定的字符,value 代表字符出现的次数
        Map<Character, Integer> map = new HashMap<>();
        for(char c : t.toCharArray()){
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
       
        int counter = map.size();//这里用map的size,而不用t的size是为了防止t是一个回文的字符串
        
        //添加begin和end值,用于后面控制窗口的大小
        int begin = 0, end = 0;
        int len = Integer.MAX_VALUE; 
       
        while(end < s.length()){//end的值,从头走到尾
            
            char c = s.charAt(end);
            
            if( map.containsKey(c) ){
                map.put(c, map.get(c)-1);//若获取的字符是给定字符串t中的字符,则将map中对应的value值减一。
                if(map.get(c) == 0) counter--;//如果取得的当前字符对应的value值为0,那么将count减一,而不去删除对应的key。
            }
            end++;
            while(counter == 0 ){//此时窗口大小起点begin还在0位置,但是end在对应的count==0的位置。count很关键,关键之处在于count==0时,所有的t中的字符都出现在对应的p中,这时,需要启动begin去寻找t中字符在p中第一次出现的位置
                
                char tempc = s.charAt(begin);
                if(map.containsKey(tempc)){
                    map.put(tempc, map.get(tempc) + 1);
                    if(map.get(tempc) > 0) counter++;
                }//此处代表begin开始逐渐移动
                
              
                if(end-begin == t.length()){//当begin与end之间的差值刚好等于t的长度,begin代表t中字符串在p中首次出现的位置,而end代表t中字符在p中最后出现的位置。
                    result.add(begin);
                }
                
                begin++;
            }
        }
        return result;
      
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值