242. Valid Anagram

1. Description

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

2. Example

Example 1

Input: s = “anagram”, t = “nagaram”
Output: true

Example 2

Input: s = “rat”, t = “car”
Output: false

3. Constraints

  • 1 <= s.length, t.length <= 5 * $10^4$
  • s and t consist of lowercase English letters.

4. Solutions

Hash Table

m = s.size(), n = t.size()
Time complexity: O(max(m, n))
Space complexity: O(1)

class Solution {
public:
    bool isAnagram(const string &s, const string &t) {
        const int m = s.size(), n = t.size();
        if (m != n) {
            return false;
        }

        array<int, 26> letter_count{};
        for (int i = 0; i < m; ++i) {
            ++letter_count[index(s[i])];
        }

        for (int i = 0; i < n; ++i) {
            --letter_count[index(t[i])];
            if (letter_count[index(t[i])] < 0) {
                return false;
            }
        }

        return true;
    }

private:
    static int index(char letter) {
        return letter - 'a';
    }
};
comments powered by Disqus