Java 17ms Sliding Window


  • 0
    K

    class Solution {

    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> res = new ArrayList<>();
        int slen = s.length(), plen = p.length(), count = plen;
        int[] table = new int[256];
        
        for (char ch: p.toCharArray()) {
            table[ch]++;
        }
        
        int left;
        for (int j = 0; j < slen; j++) {
            if (table[s.charAt(j)]-- > 0) {
                count--;
            }
            
            left = j - plen + 1;
            if (count == 0) {
                res.add(left);
            }
    
            if (left >= 0) {
                if (table[s.charAt(left)]++ >= 0) {
                    count++;
                }
            }
        }
        return res;
    }
    

    }


Log in to reply
 

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