题目:
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.
利用一个数组记录字母的出现情况,时间复杂度为O(n),空间复杂度为O(1)
解答:
class Solution {
public:
bool isAnagram(string s, string t) {
int count[26] = {0};
int lens = s.length();
int lent = t.length();
if(lens != lent)
return 0;
for(int i = 0;i < lens;++i)
{
count[s[i]-'a']++;
count[t[i]-'a']--;
}
for(int i = 0;i < 26;++i)
{
if(count[i] != 0)
return 0;
}
return 1;
}
};