7ms Java Straight-forward solution


  • 1
    public class Solution {
        public boolean isAnagram(String s, String t) {
            int[] sCharMap = new int[26]; // initialized to be 0s by default in Java!
            for(int i=0; i<s.length(); i++) {
                int mapIdx = s.charAt(i)-97;
                sCharMap[mapIdx] = sCharMap[mapIdx] + 1;
            }
            for (int i=0; i<t.length(); i++) {
                int mapIdx = t.charAt(i)-97;
                if (sCharMap[mapIdx] == 0)
                    return false;
                else
                    sCharMap[mapIdx] = sCharMap[mapIdx] - 1;
            }
            // verify the sCharMap
            int acc = 0;
            for (int i=0; i<sCharMap.length; i++)
                acc += sCharMap[i];
            return acc==0 ? true : false;
        }
    }

  • 0

    Previously I used HashMap to do char frequency counting but it turns out running 52ms!!!!!!


  • 0
    R

    I got the same situation too. Seems array is faster.


Log in to reply
 

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