题目
给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。单词是指仅由字母组成、不包含任何空格字符的最大子字符串。
例:
输入:s = "Hello World"
输出:5
解释:最后一个单词是“World”,长度为5。
方法
- index 指向字符串的尾部,result 记录最后一个单词的长度
- 循环,因为存在字符串尾部是空格的可能性,使得 index 指向最后一个单词的尾部
- 循环,不断向左移动指针,并增加单词的长度,直到指针指向空格,表示此时单词已结束
class Solution(object):
def lengthOfLastWord(self, s):
index = len(s)-1
result = 0
while index >= 0 and s[index] == ' ':
index -= 1
while index >= 0 and s[index] != ' ':
result += 1
index -= 1
return result