Java Concise


  • 0
    public class Solution {
        public List<Integer> findAnagrams(String s, String p) {
            List<Integer> res = new ArrayList<>();
            if (s == null || p == null || p.length() > s.length()) return res;
            int m = s.length();
            int n = p.length();
            int[] count = new int[26];
            for (char c : p.toCharArray()) {
                count[c - 'a']++;
            }
            for (int i = 0; i <= m - n; i++) {
                int[] copy = count.clone();
                if (helper(copy, s, i, n)) {
                    res.add(i);
                }
            }
            return res;
        }
        private boolean helper(int[] copy, String s, int index, int n) {
            for (int i = index; i < index + n; i++) {
                char c = s.charAt(i);
                copy[c - 'a']--;
                if (copy[c - 'a'] < 0) return false;
            }
            return true;
        }
    }
    

Log in to reply
 

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