给定一个仅包含大小写字母和空格 ' '
的字符串,返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
说明:一个单词是指由字母组成,但不包含任何空格的字符串。
示例:
输入: "Hello World"
输出: 5
代码:
#length-of-last-word
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
s = s.strip()
sum = ''
for i in s:
if i == ' ':
sum = ''
else:
sum += i
return len(sum)
利用split()的代码:
class Solution:
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int """
strList = s.split()
if strList:
return len(strList[-1])
return 0
思路:
1.去掉末尾空格
2.计数:记录最后一组的数量
链接: