21ms Java Accepted Solution


  • 1
        public List<Integer> findAnagrams(String s, String p) {
            List<Integer> list = new ArrayList<Integer>();
            if (s.length() < p.length()) return list;
            
            int[] count = new int[26];
            for (int i = 0; i < p.length(); i++) {
                count[p.charAt(i)-'a']++;
            }
            
            int[] count2 = new int[26];
            int n = 0;
            for (int i = 0; i < p.length(); i++) {
                int tmp = s.charAt(i)-'a';
                count2[tmp]++;
                if (count2[tmp] <= count[tmp]) n++;
            }
            if (n == p.length()) list.add(0);
            for (int i = p.length(); i < s.length(); i++) {
                int tmp = s.charAt(i)-'a';
                count2[tmp]++;
                if (count2[tmp] <= count[tmp]) n++;
                tmp = s.charAt(i-p.length())-'a';
                count2[tmp]--;
                if (count2[tmp] < count[tmp]) n--;
                if (n == p.length()) list.add(i-p.length()+1);
            }
            return list;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.