My Java Concise Sliding Window Solution


  • 0
    S
    public class Solution {
        public List<Integer> findAnagrams(String s, String p) {
            List<Integer> ret = new ArrayList<>();
            char[] ss = s.toCharArray();
            char[] pp = p.toCharArray();
            int count = pp.length;
            int[] counts = new int[256];
            for (char c : pp) {
                counts[c]++;
            }
            int i = 0;
            for (int j = 0; j < ss.length; j++) {
                if (counts[ss[j]] > 0) {
                    count--;
                }
                counts[ss[j]]--;
                while (count == 0) {
                    if (j - i + 1 == pp.length) {
                        ret.add(i);
                    }
                    counts[ss[i]]++;
                    if (counts[ss[i]] > 0) {
                        count++;
                    }
                    i++;
                }
            }
            return ret;
        }
    }
    

Log in to reply
 

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