Length of Last Word

Given a stringsconsists 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, Givens="Hello World", return5.

这道题主要是考虑一下最后是不是空格,方法是倒着找不是空格的字符并计数,如果遇到空格且计数不是0(如果遇到空格,且count是0,说明input的最后一个char是空格,例如:‘a ’),说明最后一个单词已经被计数了,所以可以返回了。

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        if len(s) == 0:
            return 0
        count = 0
        for char in reversed(s):
            if char !=' ':
                count += 1
            elif char == ' ' and count != 0:
                return count
        return count

第二种方法 先用strip() 消掉首位所有空格,然后用split函数把字符串按照空格分隔好,返回最后那个就行.

注意顺序,先strip,然后再len(l)

class Solution(object):
    def lengthOfLastWord(self, s):
        """
        :type s: str
        :rtype: int
        """
        s = s.strip()
        if len(s) == 0:
            return 0
        return len(s.split()[-1])

Last updated

Was this helpful?