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 == nullptr || &t == nullptr) {
return false;
}
int sourceArr[256] = {0};
for (std::string::iterator iter = s.begin(); iter != s.end(); iter++) {
sourceArr[*iter] ++;
}
int targetArr[256] = {0};
for (std::string::iterator iter = t.begin(); iter != t.end(); iter++) {
targetArr[*iter] ++;
}
return std::equal(std::begin(sourceArr), std::end(sourceArr), std::begin(targetArr));
}
};
时间复杂度O(n)