The 3 ms fastest AC for alphabets and 6 ms universal AC for Unicode in Java


  • 9
    A
    public class Solution {
        //6ms solution for inputs contain unicode characters
        public boolean isAnagram0(String s, String t) {
            if(s==null || t==null || s.length()!=t.length())
                return false;
            char[] sc = s.toCharArray();
            char[] tc = t.toCharArray();
            Arrays.sort(sc);
            Arrays.sort(tc);
            if(new String(sc).equals(new String(tc)))
                return true;
            return false;
        }
        
        //3ms basic ASCII 
        public boolean isAnagram(String s, String t) {
            if(s==null || t==null || s.length()!=t.length())
                return false;
            int[] alphabets = new int[256];
            char[] sc = s.toCharArray();
            char[] tc = t.toCharArray();
            for(char c : sc){
                alphabets[c]++;
            }
            for(char c : tc){
                if(alphabets[c]>0)
                    alphabets[c]--;
                else
                    return false;
            }
            return true;
        }
    }

Log in to reply
 

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