can anyone help me find my mistake (Python)


  • 0
    P

    '''
    class Solution(object):
    def findTheDifference(self, s, t):
    """
    :type s: str
    :type t: str
    :rtype: str
    """

        s = sorted(s)
        t = sorted(t)
        len_s = len(s)
        
        for i in xrange(0, len_s-1):
            if s[i]==t[i]: continue;
            elif s[i] != t[i]: return t[i];
        return t[len_s];
    

    '''

    it is said
    Input:
    "ae"
    "aea"
    Output:
    'e'
    Expected:
    'a'

    i thought i should have "a" outputed since after the sort, t will be 'aae' and compare s and t, the second element will be different, for t that is 'a'.
    can anyone point out my mistake? many thanks


  • 0
    J

    xrange(0, len_s-1) means [0], should be range(0,len_s)


  • 0
    R

    s = sorted(s)
    t = sorted(t)
    len_s = len(s)

    for i in xrange(0, len_s-1):
        if s[i]==t[i]: continue;
        elif s[i] != t[i]: return t[i];
    return t[len_s];
    

    Mistakes found :
    using t in t[len_s] after sorting t = sorted(t); there are cases like ae and aea where your t becomes aae ,
    and also you are returning return t[i]; instead of s[i];
    using range(0, len_s-1) instead of range(0, len_s);


Log in to reply
 

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