# 242. Valid Anagram

Given two strings s and t , write a function to determine if t is an anagram of s.

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true

Example 2:

Input: s = "rat", t = "car"
Output: false

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

# Solution

Approach 1: Sorting.

Approach 2: Hash table.

# Code (Python)

Approach 1:

Approach 2:

# Code (C++)

Approach 1:

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size())
            return false;
        std::sort(s.begin(), s.end());
        std::sort(t.begin(), t.end());
        return s == t;
    }
};

Approach 2:

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size())
            return false;
        unordered_map<char,int> visited;
        for (int i = 0; i < s.size(); ++i)
        {
            visited[s[i]]++;
        }
        for (int i = 0; i < t.size(); ++i)
        {
/*
            if (visited.find(t[i]) == visited.end())
                return false;
            visited[t[i]]--;
            if (visited[t[i]] == 0)
                visited.erase(t[i]);
*/
            visited[t[i]]--;
            if (visited[t[i]] < 0)
                return false;
        }
        return true;
    }
};

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size())
            return false;
        unordered_map<char,int> visited;
        for (int i = 0; i < s.size(); ++i)
        {
            visited[s[i]]++;
            visited[t[i]]--;
        }
        for (auto it = visited.begin(); it != visited.end(); ++it)
        {
            if (it->second < 0)
                return false;
        }
        return true;
    }
};