Jack Li's Blog

0242. Valid Anagrams

class Solution {
public:
    bool isAnagram(string s, string t) {
        // If size different, it isn't anagram
        if(s.size() != t.size())
            return false;
        
        unordered_map<char, int> charToCount;

        for(char c : s) {
            charToCount[c]++;
        }

        for(char c : t) {
            charToCount[c]--;
        }

        for(int i = 0; i < 26; i++) {
            char c = 'a' + i;

            if(charToCount[c] != 0)
                return false;

        }

        return true;
    }
};
class Solution {
public:
    bool isAnagram(string s, string t) {
        int mapS2count[26];

        memset(mapS2count, 0, sizeof(mapS2count));

        for(char c : s){
            mapS2count[c - 'a']++;
        }

        for(char c : t){
            mapS2count[c - 'a']--;
        }

        for(int i = 0; i < 26; i++){
            if(mapS2count[i] != 0){
                return false;
            }
        }

        return true;
    }
};