242. Valid Anagram
1. Description
Given two strings s and t , write a function to determine if t is an anagram of s.
2. Example
Example 1:
Input: s = “anagram”, t = “nagaram”
Output: true
Example 2:
Input: s = “rat”, t = “car”
Output: false
3. Note
- You may assume the string contains only lowercase alphabets.
4. Follow Up
What if the inputs contain unicode characters? How would you adapt your solution to such case?
5. Solutions
Hash Table
n = max(s.size(), t.size())
Time complexity: O(n)
Space complexity: O(1)
class Solution {
public:
bool isAnagram(const string &s, const string &t) {
if (s.size() != t.size()) {
return false;
}
unordered_map<char, int> letter_count;
for (int i = 0; i < s.size(); ++i) {
++letter_count[s[i]];
}
for (int i = 0; i < t.size(); ++i) {
--letter_count[t[i]];
if (letter_count[t[i]] < 0) {
return false;
}
}
return true;
}
};