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.
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: Using hash table
bool isAnagram(string s, string t) {
if (s.length() != t.length()) return false;
unordered_map<char, int> table;
int count = 0;
for (auto ch: s) {
table[ch] += 1;
count += 1;
}
for (auto ch: t) {
if (table.find(ch) != table.end() && table[ch] > 0) {
table[ch] -= 1;
count -= 1;
}
}
return count == 0;
}
Solution: Using array
bool isAnagram(string a, string b) {
if (a.size() != b.size()) return false;
int arr[256] = {0};
for (int i=0; i<a.size(); i++) {
arr[a[i]]++;
arr[b[i]]--;
}
for (int i=0; i<256; i++) {
if (arr[i] != 0) return false;
}
return true;
}