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

题目

给定一个字符串 s 和一个非空字符串 p,找到 s 中所有是 p 的字母异位词的子串,返回这些子串的起始索引。

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

说明:

字母异位词指字母相同,但排列不同的字符串。
不考虑答案输出的顺序。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/find-all-anagrams-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

代码

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        if(s==null||p==null){
            return null;
        }
        
        List<Integer> ansList=new ArrayList<Integer>();
        HashMap<Character,Integer> needs=new HashMap<>();
        HashMap<Character,Integer> window=new HashMap<>();
        
        for(int i=0;i<p.length();++i){
            needs.put(p.charAt(i),needs.getOrDefault(p.charAt(i),0)+1);
        }
        
        int l=0;
        int r=0;
        int matchCnt=0;
        int hopMatchCharCnt=p.length();
        while(r<s.length()){
            char c=s.charAt(r);
            if(needs.containsKey(c)){
                window.put(c,window.getOrDefault(c,0)+1);
                if(window.get(c).equals(needs.get(c))){
                    ++matchCnt;
                }
            }
            ++r;
            
            if(matchCnt==hopMatchCharCnt){
                if(r-l+1==p.length()){
                    ansList.add(l);
                }             
            }
        }
        return ansList;
    }
}

猜你喜欢

转载自www.cnblogs.com/coding-gaga/p/11324629.html