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?

bool isAnagram(string s, string t) { // time: O(n); space: O(1)
    int m = s.length(), n = t.length();
    if (m != n) return false;
    vector<int> count(26, 0);
    for (int i = 0; i < m; ++i) {
        ++count[s[i] - 'a'];
        --count[t[i] - 'a'];
    }
    for (int num : count) {
        if (num) return false;
    }
    return true;
}
// Follow-up: extend to unicode instead of only lowervase alphabets
bool isAnagram(string s, string t) { // time: O(n); space: O(1)
    int m = s.length(), n = t.length();
    if (m != n) return false;
    vector<int> count(128, 0);
    for (int i = 0; i < m; ++i) {
        ++count[s[i]];
        --count[t[i]];
    }
    for (int num : count) {
        if (num) return false;
    }
    return true;
}

Last updated

Was this helpful?