438. Find All Anagrams in a String

一、题目

  1、审题 

  

  

  2、分析

    求出所有s子串的下标,从该下标开始的连续子字符串包含 p 中的所有字符(可以无序);

    以 List方式返回所有下标;

二、解答

  1、思路

    以滑动窗口的方式统计所有符合的子串!

    public List<Integer> findAnagrams(String s, String t) {
        ArrayList<Integer> result = new ArrayList<>();
        if(s.length() < t.length())
            return result;
        
        HashMap<Character, Integer> map = new HashMap<>();
        for(char c: t.toCharArray())
            map.put(c, map.getOrDefault(c, 0) + 1);
        
        int counter = map.size();
        
        int begin = 0, end = 0;
//        int head = 0;
//        int len = Integer.MAX_VALUE;
        while(end < s.length()) {
            char c = s.charAt(end);
            if( map.containsKey(c) ) {
                map.put(c, map.get(c) - 1);
                if(map.get(c) == 0)
                    counter--;
            }
            end++;
            
            while(counter == 0) {
                char tmpc = s.charAt(begin);
                if( map.containsKey(tmpc) ) {
                    map.put(tmpc, map.get(tmpc) + 1);
                    if(map.get(tmpc) > 0)
                        counter++;
                }
                //--------
                if(end - begin == t.length())
                    result.add(begin);
                //--------
                begin++;
            }
        }
        return result;
    }
原文地址:https://www.cnblogs.com/skillking/p/11197297.html