题目:
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.
分析:
首先是要将内容全部转成小写,然后查看每个字符串中每个字母的出现次数,然后进行对比即可。
还可以把sStr和tStr数组变成一个数组,然后在该数组上进行加减,最后判断该数组是否每位都为0即可。
代码:
class Solution {
public:
bool isAnagram(string s, string t) {
int sStr[26];
int tStr[26];
for(int i=0;i<26;++i){
sStr[i]=tStr[i]=0;
}
if(s.length()!=t.length())return false;
for(int i=0;i<s.length();++i){
s[i]=tolower(s[i]);
t[i]=tolower(t[i]);
sStr[s[i]-'a']++;
tStr[t[i]-'a']++;
}
for(int i=0;i<26;++i){
if(sStr[i]!=tStr[i])return false;
}
return true;
}
};