stringanagram

Problem in solving valid anagram problem in leetcode


leetcode Problem 242

Given two strings s and t, return true if t is an anagram of s, and false otherwise.

Read the following code as my approach to solve:

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        
        if len(s) != len(t):
            return "false"
        
        dict1 = {}
        
        for key in s:
            if key in dict1:
                dict1[key] +=1
            else:
                dict1[key] =1

        dict2 = {}
        
        for key in t:
            if key in dict2:
                dict2[key] +=1
            else:
                dict2[key] =1

        for key in dict1:
            if dict1[key] != dict2.get(key, 0):
                return "false"

        for key in dict2:
            if dict2[key] != dict1.get(key, 0):
                return "false"

        return "true"

when I'm running the above code using input s = "a" and t = "ab" in my vscode editor, it gives false, which is correct. But the same code is not passing in the leetcode returning true, which is not the correct result. could you please guide, how to tweak and correct the same code??


Solution

  • you should return a boolean, not a string: i.e. say return False instead of return "false"