Untitled

 avatar
unknown
plain_text
a month ago
1.5 kB
1
Indexable
class Solution {
    
    private boolean allZero(int[] count) {
        for (int num : count) {
            if (num != 0) {
                return false;
            }
        }
        return true;
    }

    int search(String pat, String txt) {
        int k = pat.length(); // Length of the pattern
        int n = txt.length(); // Length of the text
        if (k > n) return 0; // Edge case: pattern length > text length

        int[] count = new int[26]; // Frequency array for 26 characters
        Arrays.fill(count, 0);

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

        // Check the initial window (first 'k' characters)
        int result = 0;
        if (allZero(count)) {
            result++;
        }

        // Step 2: Start sliding the window
        int i = 0;
        for (int j = k; j < n; j++) {
            count[txt.charAt(j) - 'a']--; // Add the next character (expand window)
            count[txt.charAt(i) - 'a']++; // Remove the character at the left (shrink window)
            i++; // Move the left pointer

            // Check if the current window is an anagram
            if (allZero(count)) {
                result++;
            }
        }

        return result;
    }
}
Leave a Comment