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.length() != t.length())
return 0;
int exist[30] = {0};
for(int i = 0; i < s.length(); i++)
exist[s[i]-'a']++;
for(int i = 0; i < t.length(); i++){
if(--exist[t[i]-'a'] < 0)
return 0;
}
return 1;
}
};
至於如果是unicode的話,可以用C++的unordered_map(底層以hash實現)來做。
另附:leetcode上的題解