[LeetCode] 438. Ectopic find all the letters in the word string

topic

Given a string s and a non-empty string starting index p, find all s is a substring of ectopic word letter p, and returns the substring.

String contains only lowercase letters, and the character string length p and s is not more than 20,100.

Description:

Ectopic word letters refer to the same letters, but arranged in different strings.
The order of the answers that were not considered.

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/find-all-anagrams-in-a-string
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

answer

Code

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;
    }
}

Guess you like

Origin www.cnblogs.com/coding-gaga/p/11324629.html