Beats 97% of Java programs


  • 0
    L

    Avoid sorting as it will get you nlogn+klogk. We should look for n+k here instead:

    public boolean isAnagram(String s, String t) {
            if(s==null || t == null) {
                return false;
            }
    
           int[] counts = new int[26];
           for(char c : s.toCharArray()) {
               counts[c-'a']++;
           }
           
           for(char c : t.toCharArray()) {
               counts[c-'a']--;
           }
           
           for(int i : counts) {
               if(i!=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.