Iterative - Java - Sliding window.


  • 0
    public class Solution {
        public List<Integer> findAnagrams(String s, String p) {
            int[] pChars = new int[26];
            List<Integer> pIndices = new ArrayList<>();
            // Initialize with String p frequencies.
            for (char c: p.toCharArray())
            {
                pChars[c - 'a']++;
            }
            int start = 0, end = 0;
            int pLen = p.length(); // Number of matches needed.
    
            while(end < s.length())
            {
               if (pChars[s.charAt(end++) - 'a']-- >= 1) 
                    pLen--; // If current char is a match.
                if (pLen == 0 && (end - start) == p.length())
                    pIndices.add(start); // Anagram Matched. 
              if (end - start == p.length()) 
              {
                if (pChars[s.charAt(start)-'a']++ >= 0)
                    pLen++; // Reset the count and increment the matches needed.
                start++;
              }
            }
            return pIndices;
        }
    }

Log in to reply
 

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