O(n)-----------simple Java Map solution


  • 0
    H
     public boolean isAnagram(String s, String t) {
        int len1=s.length(),len2=t.length();
        if(s==null||t==null||len1!=len2)
          return false;
          HashMap<Character,Integer> map=new HashMap<Character,Integer>();
          for(int i=0;i<len1;i++){
              char c=s.charAt(i);
              if(map.get(c)==null)
                map.put(c,1);
              else
                map.put(c,map.get(c)+1);
          }
          
          for(int i=0;i<len2;i++){
              char c=t.charAt(i);
              if(map.get(c)==null)
                return false;
              else{
                int num=map.get(c);
                if(num==0)
                  return false;
                else
                  map.put(c,map.get(c)-1);
              }
          }
          
         return true;
    }

  • 1
    M

    you don't need to iterate through the last keySet. you could just return true after the second for loop.


  • 0
    H

    yes,you are right! thank you for your advice!!


Log in to reply
 

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