zoukankan      html  css  js  c++  java
  • 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;
        }
  • 相关阅读:
    今天,你ak了吗?①
    线段树模板
    DP(关于字符串,数字串的)
    Leedsdiscussion
    高数积分求旋转体体积
    tiny mission
    莫队+数组低级化的 优先队列
    LAB2
    Leedslecturepronouncation
    Eclipse Access Restriction
  • 原文地址:https://www.cnblogs.com/skillking/p/11197297.html
Copyright © 2011-2022 走看看