Length of Last Word

题目描述

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example,

s = "Hello World",
return 5.

解题方法

easy question

Solution

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0
        s = s.strip()
        length = len(s)
        if length == 0:
            return 0

        result = 0
        p = length - 1
        while p >= 0:
            if s[p] != ' ':
                p -= 1
                result += 1
            else:
                break

        return result

Reference