【题目】
来源:leetcode
链接:https://leetcode-cn.com/problems/valid-anagram/
【代码】
这个代码简洁但是时间效率差
class Solution {
public:
bool isAnagram(string s, string t) {
sort(s.begin(),s.end());
sort(t.begin(),t.end());
return s==t;
}
};
【hash法】这个代码略微繁琐但是时间效率比上面一种方法高很多
执行用时 :4 ms, 在所有 C++ 提交中击败了99.63% 的用户
内存消耗 :7.3 MB, 在所有 C++ 提交中击败了100.00%的用户
class Solution {
public:
int hash[26]={0};
bool isAnagram(string s, string t) {
if(s.size()!=t.size())
return false;
for(auto x:s)
hash[x-'a']++;
for(auto x:t){
hash[x-'a']--;
if(hash[x-'a']<0)
return false;
}
return true;
}
};