Sliding window approach similar to 'Find All Anagrams in a String'


  • 0
    G

    Very similar approach to https://leetcode.com/problems/find-all-anagrams-in-a-string/#/description

    public boolean checkInclusion(String s1, String s2) {
        int[] hash = new int[26];
        for (char c : s1.toCharArray()) {
            hash[c - 'a']++;
        }
        int start = 0, end = 0, count = s1.length();
        while (end < s2.length()) {
            if (hash[s2.charAt(end++) - 'a']-- >= 1) count--;
            if (count == 0) return true;
            if (end - start == s1.length() && hash[s2.charAt(start++) - 'a']++ >= 0) count++;
        }
        return false;
    }
    

Log in to reply
 

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