Java solution using sliding window


  • 0
    C
    public boolean checkInclusion(String s1, String s2) {
            if(s2.length() < s1.length()){
                return false;
            }
            
            int[] arr1 = new int[26], arr2 = new int[26];
            
            for(char ch : s1.toCharArray()){
                arr1[ch - 'a']++;  
            }
            
            int idx = s1.length() - 1;
            for(int i=0; i<idx; i++){
                arr2[s2.charAt(i) - 'a']++;
            }
            
            int beg = 0;
            while(idx < s2.length()){
                arr2[s2.charAt(idx++) - 'a']++;
                
                if(Arrays.equals(arr1, arr2)){
                    return true;
                }
                
                arr2[s2.charAt(beg++) - 'a']--;
            }
            
            return false;
        }
    

Log in to reply
 

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