Python Valid Anagram (48ms)


  • 2
    E
    class Solution(object):
        def isAnagram(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: bool
            """
            while s != '':
                if len(s) != len(t):
                    return False
                tmp = s[0]
                s = s.replace(tmp, '')
                try:
                    t = t.replace(tmp, '')
                except:
                    return False
    
            if t != '':
                return False
            else:
                return True

  • 0
    9

    Excuse me!
    I use the same function .replace()
    but the result is "Time Limit Exceeded "
    Can you give me any suggestion?

    class Solution(object):

    def isAnagram(self, s, t):
        if len(s)!=len(t):
            return False
        for i in s:
            s=s.replace(i,"",1
            t=t.replace(i,"",1)
        if s==t:
            return True
        else:
            return False

Log in to reply
 

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