7ms java solution using sliding window approach


  • 0
    S
    public boolean isAnagram(String s, String t){
            if(s.length() != t.length()){
                return false;
            }
            int[] charsInT = new int[26];
            int left = 0, right = 0, count = t.length();
            for(int i  = 0 ; i < t.length() ;i++){
                charsInT[t.charAt(i)-'a']++;
            }
            while(right < s.length()){
                if(charsInT[s.charAt(right++)-'a']-- > 0){
                    count--;
                }
                if(count == 0){
                    return true;
                }
                if(right - left == t.length() && count != 0){
                    return false;
                }
            }
            return true;
        }
    

Log in to reply
 

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