Java solution for Unicode


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

  • 0
    S

    c++ solution for unicode:

    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) return false;
        unordered_map<char, int> count;
        for (int i = 0; i < s.size(); i++){
            if (count.find(s[i]) == count.end()){
                count[s[i]] = 1;
            } else {
                count[s[i]]++;
            }
            
            if (count.find(t[i]) == count.end()){
                count[t[i]] = -1;
            } else {
                count[t[i]]--;
            }
        }
        
        for (auto& i : count){
            if ( i.second != 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.