/*Hash Table. 时间复杂度O(n).
用一个Hash表记录s中每个字母出现的次数,然后在扫描t数组检查它们字母个数是否一样。*/
class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<char, int> count;
for(int i = 0; i < s.size(); ++i) ++count[s[i]];
for(int i = 0; i < t.size(); ++i) --count[t[i]];
for(unordered_map<char, int>::iterator it = count.begin(); it != count.end();
++it){
if(it->second != 0) return false;
}
return true;
}
};
LeetCode之Valid Anagram
最新推荐文章于 2022-10-31 13:17:13 发布