242 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.
Solution
O(N) time, O(1) space
class Solution {
public:
bool isAnagram(string s, string t) {
int prime[26] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101};
int sum = 0;
int ns = s.size(), nt = t.size();
for ( int i = 0; i <= ns-1; i++ ) {
int j = s[i] - 'a';
sum += prime[j] * (j+1);
}
for ( int i = 0; i <= nt-1; i++ ) {
int j = t[i] - 'a';
sum -= prime[j] * (j+1);
}
return ( sum == 0 );
}
};
O(N) time, O(N) space
class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<char, int> map;
int ns = s.size(), nt = t.size();
if ( ns != nt ) return false;
for ( int i = 0; i <= ns-1; i++ ) {
if ( map.find(s[i]) == map.end() ) map[s[i]] = 1;
else map[s[i]] += 1;
}
for ( int i = 0; i <= nt-1; i++ ) {
if ( map.find(t[i]) == map.end() ) return false;
map[t[i]] -= 1;
if ( map[t[i]] == -1 ) return false;
}
return true;
}
};