题目
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.
思路
我们可以统计各个字符出现的频次,如果两个字符串之间每个字符出现次数都一样,那必然可以通过调换位置得到。
由于题目中规定的是小写字母用例,所以这道题用一个int[26]的数组统计频次即可。
代码
class Solution {
public:
bool isAnagram(string s, string t) {
int count1[26]={0},count2[26]={0};
for(int i=0;i<s.size();i++)
count1[s[i]-'a']++;
for(int i=0;i<t.size();i++)
count2[t[i]-'a']++;
for(int j=0;j<26;j++){
if(count1[j]!=count2[j])
return false;
}
return true;
}
};