Data Structre_Sliding Window - xwu36/LeetCode GitHub Wiki

Problem #567. Permutation in String

Given two strings s1 and s2, write a function to return true if s2 contains the permutation of s1. In other words, one of the first string's permutations is the substring of the second string.

public class Solution {
    public boolean checkInclusion(String s1, String s2) {
        int len = s1.length();
        int[] counter = new int[26];
        for(int i = 0; i < s1.length(); i++)
            counter[s1.charAt(i) - 'a']++;
        int left = 0;
        int right = 0;
        while(right < s2.length()){
            char cur_r = s2.charAt(right);
            counter[cur_r - 'a']--;
            right++;
            if(counter[cur_r - 'a'] < 0 || left <= right - len){
                while(left < right - len){
                    char cur_l = s2.charAt(left);
                    counter[cur_l - 'a']++;  
                    left++;
                }
                if(left == right - len && valid(counter)){
                    return true;
                }
            }
        }
        return false;
    }
    
    private boolean valid(int[] counter1){
        for(int value : counter1){
            if(value != 0)
                return false;
        }
        return true;
    }
}

3. Longest Substring Without Repeating Characters