Sharing my Solution. Beats 99.90% python solutions


  • 2
    P

    class Solution(object):

    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s)==len(t):
            for char in set(s):
                if s.count(char)!=t.count(char):
                    return False
            return True
        else:
            return False

  • 0
    P

    By converting 's' into a Set, we only compare against the unique values in s, and hence reduce the number of comparisons.


  • 0
    B

    What if two strings are "btt" and "tbb" ? Your solution will still return True but the answer is false.


  • 0
    P

    It returns false. You should try dry running it once. It converts the first one into a set. Hence set(s) contains 'b' and 't'. It then checks the count of 'b' in both s and t. Since the count is not equal, it returns false.


  • 0
    B

    Oops! Yeah I guess I overlooked it the first time I read it.


  • 0
    S

    Looks you go through whole string for every distinct char. Can't tell why it's so fast...


  • 0
    I

    agree, it makes no sense this solution beats 99.90% others. We need more reasonable test case.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.