问题描述:
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.
问题求解:
class Solution {
public:
bool isAnagram(string s, string t) {
if(s.size() != t.size()) return false;
int cmp[26] = {0};//26个字母对应的cmp全初始化为0
for(int i=0;i<s.size();i++)
{//s和t中字母对应的cmp一个加1,一个减1
cmp[s[i]-'a']++;
cmp[t[i]-'a']--;
}//如果s和t中字母都相同,则26个字母cmp的值最后不会改变
for(int j=0;j<26;j++)
{//若不相等,则说明s和t不是变位词
if(cmp[j] != 0) return false;
}
return true;
}
};