Untitled

 avatar
unknown
plain_text
a month ago
1.5 kB
2
Indexable
import java.util.*;

class Solution {
    public List<Integer> findAnagrams(String s, String p) {
        List<Integer> result = new ArrayList<>();
        int n = s.length();
        int k = p.length();
        if (k > n) return result; // If pattern is longer than the string, return empty list

        int[] count = new int[26]; // Frequency array for 26 lowercase English letters

        // Step 1: Process the first 'k' characters of p and s
        for (int idx = 0; idx < k; idx++) {
            count[p.charAt(idx) - 'a']++; // Increment frequency for pattern
            count[s.charAt(idx) - 'a']--; // Decrement frequency for string
        }

        // Check the initial window
        if (areAllZero(count)) {
            result.add(0);
        }

        // Step 2: Start sliding the window
        int i = 0;
        for (int j = k; j < n; j++) {
            count[s.charAt(j) - 'a']--; // Expand the window by adding the new character
            count[s.charAt(i) - 'a']++; // Shrink the window by removing the old character
            i++; // Move the left pointer

            // Check if the current window is an anagram
            if (areAllZero(count)) {
                result.add(i);
            }
        }

        return result;
    }

    // Helper function to check if all elements in the count array are zero
    private boolean areAllZero(int[] count) {
        for (int num : count) {
            if (num != 0) return false;
        }
        return true;
    }
}
Leave a Comment