Python solution, beginner's level, 44 ms


  • 0
    K

    The code below got passed.

    def lengthOfLastWord(self, s):
    
        while (len(s)>0 and s[-1]==' '):         # remove spaces from the end
            s = s[:-1]
    
        if len(s) != 0:                          # check if empty string
            i=len(s)-1
            a=0                                             
            while (s[i] != ' ' and i > -1):      # count reversely and stop counting if met a space
                a=a+1                            # count
                i=i-1
        else:
            return 0
            
        return a

Log in to reply
 

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