【leetcode】Length of Last Word

时间:2023-03-09 08:00:31
【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.

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.

解题思路:

注意空格就好

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])