My solution in python


  • 2

    here is my simple accepted solution, the idea is included in the comment

    class Solution:
        # @param s, a string
        # @return an integer
        def lengthOfLastWord(self, s):
            # get rid of the " " before or after
            # split the string into words
            t=s.strip(" ").split(" ")
            # find the last word
            # return its length
            return len(t[len(t)-1])

  • 0
    M

    You do not deal with the " " input.
    And you can just use s.split() instead of s.strip(" ").split(" ").


  • 0

    the input of " " will return 0 as desired. As for s.split(), the input of "a b " will get a couple of "" at the end, while by using strip(" ") you can get rid of the unwanted ""s


  • 0
    C
    This post is deleted!

  • 0
    S

    Thanks for your post. However it would be better to share solution with correct code format and elaborated thoughts. Please read the Discuss FAQ for more info. Take a look at good sharing example


  • 0
    W

    There is my ac code.

    class Solution:
        def lengthOfLastWord(self, s):
    
            if(" " in s):
                tmp = s.split(" ")
                for i in range(len(tmp) - 1, -1, -1):
                    if len(tmp[i]) != 0:
                        return len(tmp[i])
                return 0
            else:
                return len(s)

Log in to reply
 

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