[LeetCode] 438異所は、単語列のすべての文字を見つけます

タイトル

文字列sと非空の文字列の開始インデックスpが与えられ、すべてが異所性ワード文字pのサブですよ、と部分文字列を返します見つけます。

文字列が小文字のみが含まれており、文字列の長さp、sは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