Untitled
public class Solution { public boolean checkInclusion(String s1, String s2) { int n = s2.length(), k = s1.length(); if (k > n) return false; // Frequency count for s1 int[] freqS1 = new int[26]; for (char c : s1.toCharArray()) { freqS1[c - 'a']++; } // Sliding window frequency count for s2 int[] freqWindow = new int[26]; int i = 0, j = 0; // Process the first k elements while (j < k) { freqWindow[s2.charAt(j) - 'a']++; j++; } // Compare the first window if (matches(freqS1, freqWindow)) return true; // Slide the window while (j < n) { freqWindow[s2.charAt(j) - 'a']++; // Add the new character freqWindow[s2.charAt(i) - 'a']--; // Remove the old character j++; i++; // Check if current window matches if (matches(freqS1, freqWindow)) return true; } return false; } // Helper function to compare two frequency arrays private boolean matches(int[] freqS1, int[] freqWindow) { for (int i = 0; i < 26; i++) { if (freqS1[i] != freqWindow[i]) return false; } return true; } }
Leave a Comment