Java Sliding Window Solution


  • 0
    F
    public boolean checkInclusion(String s1, String s2) {
    	if(s1 ==null || s2==null || s1.length()>s2.length())
    		return false;
    	int[] cs = new int[26];
    	for(char c: s1.toCharArray()){
    		cs[c-'a']++;
    	}
    	
    	int i=0, j=0, count = s1.length();
    	char[] chars = s2.toCharArray();
    	while(j<s2.length()){
    		int index = chars[j]-'a';
    		cs[index]--;
    		if(cs[index]>=0)
    			count--;
    		j++;
    		while(count ==0){
    			if(j-i == s1.length())
    				return true;
    			index = chars[i]-'a';
    			cs[index]++;
    			if(cs[index]>0)
    				count++;
    			i++;
    		}
    	}
    	return false;                
    }

Log in to reply
 

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