简体   繁体   中英

Leetcode is showing me a key error, but it works fine in my text editor. How can I fix this?

I am doing the Valid Anagram question on Leetcode: https://leetcode.com/problems/valid-anagram/

Here is the solution I have come up with:

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))

This works fine for me in my text editor, however when I copy/paste it into Leetcode, I get this error:

Runtime Error

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)

Is this error due to formatting? I cannot figure it out for the life of me!

This error means that item is not a key in hashmap2 , which will happen whenever there's a letter in s that isn't in t . You need to check for that.

You also need to check for letters that are in t that aren't in s .

for item in hashmap:
    if item not in hashmap2 or hashmap[item] != hashmap2[item]:
        return False
for item in hashmap2:
    if item not in hashmap:
        return False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM