Python using replace (runtime 99%)


  • 0
    J

    To avoid checking the same letters repeatedly, for each letter in s, I remove them all in both s, and t, and compare len(s) and len(t) afterwards. If they are equal, then means the removed letter is the one.

    If after removing all letters in s, there is still one letter left in t, then that's the added letter.

    class Solution(object):
        def findTheDifference(self, s, t):
            """
            :type s: str
            :type t: str
            :rtype: str
            """
    
            while len(t)-len(s)==1 and len(s)>0:
                ss=s[0]
                s=s.replace(ss,'')
                t=t.replace(ss,'')
            if len(t)==len(s):
                return ss
            else:
                return t
    

Log in to reply
 

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