Java solution handles unicode with hashmap


  • 1
    S

    It's not elegant one, yet I try a lot to use hashmap in Java as I think it is more tricky than that in C++.

    public class Solution {
    public boolean isAnagram(String s, String t) {
        if(s.length()!=t.length() || s==null || t==null)
            return false;
        if(s.length()==0)
            return true;
        int n = s.length();
    
       java.util.HashMap<Character, Integer> charset = new java.util.HashMap<Character, Integer>();
        for(int i=0; i<n; i++){
        	charset.put(s.charAt(i), charset.containsKey(s.charAt(i)) ? charset.get(s.charAt(i))+1 : 1);
        	charset.put(t.charAt(i), charset.containsKey(t.charAt(i)) ? charset.get(t.charAt(i))-1 : -1);
        }
    
        for(int i: charset.values()){
        	if (i!=0)
        		return false;
        }
        return true;
    }
    

    }


Log in to reply
 

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