【leetcode】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.spa

If the last word does not exist, return 0.code

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

For example,
Given s = "Hello World",
return 5.it

解題思路:

注意空格就好io

class Solution:
    # @param s, a string
    # @return an integer
    def lengthOfLastWord(self, s):
        if len(s) == 0:
            return 0
        i = len(s) -1
        while s[i] == ' ':
            
            if i == 0:
                return 0
            i -= 1
        res = s[0:i+1].split(' ')
        return len(res[-1])
相關文章
相關標籤/搜索