【题目】
来源: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;
}
};

本文探讨了LeetCode上的一道经典问题——有效字母异位词,提供了两种解决方案:排序法和hash计数法。排序法简洁但时间效率较低,而hash计数法虽然代码稍显复杂,但在时间和空间效率上表现更佳,分别击败了99.63%和100.00%的用户。

被折叠的 条评论
为什么被折叠?



