给定一个字符串, 包含大小写字母、空格’ ‘,请返回其最后一个单词的长度。
如果不存在最后一个单词,请返回 0 。
思路:先判断字符串长度是否为零,为零返回。从最后一个单词开始,是字母话+1,否则返回。
class Solution:
# @param {string} s A string
# @return {int} the length of last word
def lengthOfLastWord(self, s):
# Write your code here
lenword = 0
isAlpha = False
for i in range(len(s)-1, -1, -1):
tmp = s[i]
if isAlpha == True and tmp.isalpha() == False:
break
if tmp.isalpha():
isAlpha = True
lenword += 1
return lenword