原题:
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?
解决方法:
用两个数组来记录每个字符串字符出现的次数,如何比较两个数组即可。
代码:
bool isAnagram(string s, string t) {
if (s.size() != t.size())
return false;
int a[26] = {0}, b[26] = {0};
for(int i = 0; i < s.size();i++){
a[s[i] - 'a']++;
b[t[i] - 'a']++;
}
for(int i = 0; i < 26; i++){
if (a[i] != b[i])
return false;
}
return true;
}