Python 36 ms solution with explanation


  • 0
    F

    Start out by finding whether word is empty, all space, or None.
    Then, remove rightmost whitespace (or skip it if you'd like). Once that is done, you need to start from the end and count the number of characters in the string.

    Here is the solution:

    class Solution(object):
        def lengthOfLastWord(self, s):
            """
            :type s: str
            :rtype: int
            """
            if ((s == "") or (s == None) or (s.isspace())):
                return 0
                
            length = 0
            s = s.rstrip()
            for i in xrange(len(s)-1,-1,-1):
                if (s[i] != " "):
                    length += 1
                else:
                    break
            return length

Log in to reply
 

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