leetcode笔记--Length of Last Word

题目:难度(Easy)

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, 
Given s = "Hello World",
return 5.
Tags:String

分析:最后一个单词的理解:最后一个单词的后面和前面均允许有空白符;如果串中只有一个单词也是最后一个单词;全是空白符就一个单词也没有,也就没有最后一个单词之说了。

代码实现:

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        #返回最后一个单词的长度,如果没有最后一个单词,返回0
        #先去除两侧的空白字符,返回副本
        s = s.strip()
        if len(s) == 0:
            return 0
        i = len(s) - 1
        while i >= 0:
            if s[i] != ' ':
                i -= 1
            else:
                break
        return len(s) - i - 1


你可能感兴趣的:(LeetCode,python,String)