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) {
int slen = s.size();
int tlen = t.size();
if (slen != tlen) {
return false;
}
sort(s.begin(), s.end());
sort(t.begin(), t.end());
int i = 0;
while (i < slen && s[i] == t[i]) i++;
return i == slen;
}
};
改进一下:
class Solution {
public:
bool isAnagram(string s, string t) {
int slen = s.size();
int tlen = t.size();
if (slen != tlen) {
return false;
}
int count[128] = {0};
for (int i=0; i<slen; i++) {
count[s[i]]++;
}
for (int i=0; i<tlen; i++) {
if (--count[t[i]] < 0) {
return false;
}
}
return true;
}
};