题目:
给定一个字符串,字符串中包含空格和单词,计算最后一个单词的长度。
解题思路:
从最后一个单词开始计算长度,直到检测到空格,最后一个单词计算结束,返回当前的长度。
代码(Python):
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
count = 0
for i in range(len(s)):
temp = i+1
if s[-temp]!=' ':
count = count+1
if s[-temp]==' ' and count!=0:
return count
return count