Leetcode 242. Valid Anagram (Easy) (cpp)
Tag: Hash Table, Sort
Difficulty: Easy
/*
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?
*/
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.empty() != t.empty() || s.length() != t.length()) {
return false;
}
if (s.empty() && t.empty()) {
return true;
}
unordered_map<char, int> mapping;
for (auto cha : s) {
mapping[cha] += 1;
}
for (auto cha : t) {
if (mapping[cha] == 0) {
return false;
}
else {
mapping[cha]--;
}
}
return true;
}
};
class Solution {
public:
bool isAnagram(string s, string t) {
if (s.empty() != t.empty() || s.length() != t.length()) {
return false;
}
if (s.empty() && t.empty()) {
return true;
}
vector<int> cnt(26, 0);
for(int i = 0; i < s.size(); i++) {
cnt[s[i]-'a']++;
}
for(int i = 0; i < t.size(); i++) {
if(cnt[t[i]-'a'] == 0) return false;
cnt[t[i]-'a']--;
}
return true;
}
};