原題:
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;
}