题目描述:给定一个字符串, 包含大小写字母、空格' ',请返回其最后一个单词的长度。如果不存在最后一个单词,请返回 0 。
样例:给定 s = "Hello World",返回 5。
可以这样设计:从字符串最后开始往前找,找到第一个是字母的位置,从这个位置开始,继续向前遍历,每遍历一个字母,计数+1,直到遍历到第一个不是字母的位置为止(其实这个程序也可以解决除了字母和空格外有其他字符的情况)
思路上没有任何特别的,给出代码就行:
class Solution:
# @param {string} s A string
# @return {int} the length of last word
def lengthOfLastWord(self, s):
index = -1
count = 0
n = len(s)
while index >= -n:
if s[index].isalpha():
break
index -= 1
while index >= -n:
if s[index].isalpha():
count += 1
index -= 1
else:
break
return count
# Write your code here