Simple fast java solution (beats 97%)


  • 24
    J
    public boolean isAnagram(String s, String t) {
        
        int[] charsMap = new int['z'-'a'+1];
        
        for(char c: s.toCharArray()) {
            int pos = c - 'a';
            charsMap[pos]++;
        }
        
        for(char c: t.toCharArray()) {
            int pos = c - 'a';
            charsMap[pos]--;
        }
        
        for(int count: charsMap) {
            if(count != 0) {
                return false;
            }
        }
        
        return true;
    }

  • 0
    N

    Hi~ I find a little problem in your code. Are you sure you take 'A'-'Z' into consideration?
    (Line 6: the pos is negative if the character is upper case)


  • 0
    J

    You are correct, however I did this way because of the following note in the problem:

    Note:
    You may assume the string contains only lowercase alphabets.


  • 0
    F
    This post is deleted!

  • 0
    R

    That's a neat solution. Do you know how you would adapt it if there were unicode characters too?

    I'm asking since I have no idea. Thanks.


  • 2
    J

    I would probably use a Map instead of an array: first you create a map with a counter per each character. Then you run the map against the second string, and every time a character reaches zero, you remove the element from the map. Also, if a character is not in the map anymore, then it's no an anagram. At the end of the operations, if the map is empty, then it's an anagram.


  • -4
    A

    Great solution! Thanks for sharing, even though now it only beats 34%. I guess there are many new better solutions out there, but seems like the authors don't want to share them.


Log in to reply
 

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