242. Valid Anagram (Easy)

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.

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 1: Hash Table

version 1: unordered_map 16ms

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

        for (auto& a: m) {
            if (a.second) return false;
        }
        return true;
    }
};

version 2: 16ms

class Solution {
public:
    bool isAnagram(string s, string t) {
        if (s.size() != t.size()) return false;
        vector<int> m(26,0);
        for (int i = 0; i < s.size(); ++i) {
            ++m[s[i]-'a']; --m[t[i]-'a'];
        }

        for (auto& a: m) {
            if (a) return false;
        }
        return true;
    }
};

Solution 2: Brute Force 29ms

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

results matching ""

    No results matching ""