LeetCode Valid Anagram


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

For example,
s = “anagram”, t = “nagaram”, return true.
s = “rat”, t = “car”, return false.

You may assume the string contains only lowercase alphabets.

The original problem is here.

The original code is here.

My Solution

I solve this problem in C++, as below:

*Valid Anagram 
*Author: shuaijiang
*Email: zhaoshuaijiang8@gmail.com
using namespace std;

class Solution {
    bool isAnagram(string s, string t) {
        int size1 = s.size();
        int size2 = t.size();
        map<char, int> myMap;
        if(size1 != size2)
            return false;
        if(size1 == 1 && size2 == 1) {
            if(s[0] == t[0])
                return true;
                return false;
        for(int i=0;i<size1;i++){
            if(myMap.find(s[i]) == myMap.end())
                myMap[s[i]] = 1;
                myMap[s[i]] += 1;

        for(int i=0;i<size1;i++){
            if(myMap.find(t[i]) == myMap.end())              
                return false;
            else if(myMap[t[i]] == 0)
                return false;
                myMap[t[i]] --;
        return true;


To solve the problem, use a map to save the count of each alphabet in string s. Then, traversal string t, and find each alphabet in the map and minus the count of it. If the alphabet does not exist in the map or the count of the alphabet is zeros, then return false. Finally, return true.