My Python Solution


  • 0
    D
    class Solution:
    # @param s, a string
    # @return an integer
    def lengthOfLastWord(self, s):
        k = s.split()
        if len(k) != 0:
            return len(k[len(k)-1])
        else:
            return 0

  • 2
    C

    You can use python indexing format

    len(k[-1])  # same as k[len(k)-1]
    

    Following is my python solution:

        def lengthOfLastWord(self, s):
        try:
            return len(s.split()[-1])
        except IndexError as e:
            return 0

  • 1
    C
    class Solution:
        def lengthOfLastWord(self, s):
            return len(([""] + s.split())[-1])

Log in to reply
 

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