Given two strings s and t, return true if t is an anagram of s, and false otherwise.
- sort both strings and compare them.
- if they are equal, return true else false.
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(),s.end());
sort(t.begin(),t.end());
return s==t?true:false;
}
};
- We store frequency of each character in a hash table.
- Decrement the frequency of each character in hash table which is in the t.
- If any frequency is not zero, return false.
class Solution {
public:
bool isAnagram(string s, string t) {
vector<int> a(26,0);
if(s.size()!=t.size()) return false;
for(auto &x:s){
a[x-'a']++;
}
for(auto &x:t){
--a[x-'a'];
}
for(auto &x:a){
if(x>=1) return false;
}
return true;
}
};
- first confirm sizes of both strings is same.
- We can avoid 3rd loop by checking if the frequency of each character less than 0 then return false.
- return true by default.
class Solution {
public:
bool isAnagram(string s, string t) {
vector<int> a(26,0);
if(s.size()!=t.size()) return false;
for(auto &x:s){
a[x-'a']++;
}
for(auto &x:t){
if(--a[x-'a']<0) return false;
}
return true;
}
};