You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LeetCode有效字母异位题出现KeyError,本地运行正常如何解决?

解决LeetCode有效字母异位词题目中的KeyError问题

我正在做LeetCode的有效字母异位词题目,写了如下代码,本地运行正常,但粘贴到LeetCode后出现KeyError。

我的代码:

class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False
        hashmap = dict()
        hashmap2 = dict()
        for char in s:
            if char in hashmap:
                hashmap[char] = hashmap[char] + 1
            else:
                hashmap[char] = 1
        for char in t:
            if char in hashmap2:
                hashmap2[char] = hashmap2[char] + 1
            else:
                hashmap2[char] = 1
        for item in hashmap:
            if hashmap[item] != hashmap2[item]:
                return False
        return True

obj1 = Solution()
s = "aacc"
t = "cacc"
print(obj1.isAnagram(s, t))

报错信息:

KeyError: u't'
    if hashmap[item] != hashmap2[item]:
Line 23 in isAnagram (Solution.py)
    ret = Solution().isAnagram(param_1, param_2)
Line 49 in _driver (Solution.py)
    _driver()
Line 59 in <module> (Solution.py)

这个错误不是格式问题,是代码逻辑存在漏洞:

  • 你只遍历了统计s字符的哈希表hashmap的键,去和统计t字符的hashmap2比较,但如果s中存在t没有的字符(虽然长度相等,但这种情况会导致hashmap2缺少对应键),访问hashmap2[item]时就会触发KeyError。比如当s包含某个字符,但t里没有该字符,hashmap2中就没有这个键,遍历hashmap的键时就会找不到对应值。

修正方案

方案1:检查所有存在的字符键

合并两个哈希表的键,遍历所有可能的字符,确保每个字符的计数都相等:

class Solution(object):
    def isAnagram(self, s, t):
        if len(s) != len(t):
            return False
        hashmap = dict()
        hashmap2 = dict()
        for char in s:
            hashmap[char] = hashmap.get(char, 0) + 1
        for char in t:
            hashmap2[char] = hashmap2.get(char, 0) + 1
        # 遍历所有出现过的字符键
        for char in set(hashmap.keys()).union(set(hashmap2.keys())):
            if hashmap.get(char, 0) != hashmap2.get(char, 0):
                return False
        return True

方案2:只用一个哈希表(更高效)

先统计s的字符计数,再遍历t的字符减少计数,最后检查所有计数是否为0:

class Solution(object):
    def isAnagram(self, s, t):
        if len(s) != len(t):
            return False
        count = {}
        for char in s:
            count[char] = count.get(char, 0) + 1
        for char in t:
            count[char] = count.get(char, 0) - 1
            # 提前终止:如果某个字符计数为负,说明t中该字符更多
            if count[char] < 0:
                return False
        return all(v == 0 for v in count.values())

方案3:排序后直接比较(代码最简洁)

如果两个字符串是字母异位词,排序后必然完全相同:

class Solution(object):
    def isAnagram(self, s, t):
        return sorted(s) == sorted(t)

内容的提问来源于stack exchange,提问作者Smitty_Code

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 04:55:30