Java Solution Using HashMap


  • 4
    C
    public class Solution {
        public boolean isAnagram(String s, String t) {
            char[] arr1=s.toCharArray();
            char[] arr2=t.toCharArray();
            HashMap<Character,Integer> h=new HashMap<Character,Integer>();
            if(arr1.length != arr2.length)
            return false;
           for(int i=0;i<arr1.length;i++){
                if(h.get(arr1[i])!= null)
                h.put(arr1[i],(h.get(arr1[i]))+1);
                else
                h.put(arr1[i],1);
            }
            for(int i=0;i<arr2.length;i++){
                if(h.get(arr2[i]) ==null)
                return false;
                else if(h.get(arr2[i])==0)
                return false;
                else
                h.put(arr2[i],(h.get(arr2[i]))-1);
            }
            return true;
        }
    }

  • 0
    H

    Similar idea and I think a little change can make it more concise. Like change the content in first loop to h.put(arr1[i],res.getOrDefault(arr1[i],0)+1);


Log in to reply
 

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