为何最后一个for循环中unordered_map的size持续增大?
问题分析与解决方案:unordered_map遍历导致size持续增大
问题根源
你的代码核心错误出在unordered_map的遍历逻辑上:
- 你声明的
sm是unordered_map<char, int>,键类型是字符,但你用int j从0开始循环,通过sm[j]访问元素。 - C++中
unordered_map的operator[]有个特性:如果访问的键不存在,会自动插入一个新的键值对(键为传入的参数转换为char后的值,值默认初始化为0)。 - 所以每次循环都会往
sm里插入新的字符键(比如j=0对应ASCII空字符'\0',j=1对应'\x01'等),导致sm.size()不断增大,循环条件j < sm.size()永远无法满足,陷入无限循环。
修正后的代码(正确遍历unordered_map)
用C++范围for循环直接遍历键值对,避免错误的键访问:
class Solution { public: bool isAnagram(string s, string t) { if(s.size() != t.size()){ return false; } unordered_map<char,int> sm; unordered_map<char,int> tm; for (int i = 0; i < s.size(); i++){ sm[s[i]]++; tm[t[i]]++; } // 正确遍历unordered_map的键值对 for (const auto& kv : sm) { char c = kv.first; if (sm[c] != tm[c]) { return false; } } return true; } };
更高效的替代方案(数组代替哈希表)
因为字母异位词通常只涉及26个小写字母(假设题目限定为小写),用数组代替unordered_map速度更快、开销更低:
class Solution { public: bool isAnagram(string s, string t) { if (s.size() != t.size()) return false; int count[26] = {0}; for (int i = 0; i < s.size(); ++i) { count[s[i] - 'a']++; count[t[i] - 'a']--; } for (int num : count) { if (num != 0) return false; } return true; } };
内容的提问来源于stack exchange,提问作者Jayden
相关产品推荐
相关产品推荐

