LeetCode 58. 最后一个单词的长度

2022-08-30  本文已影响0人  草莓桃子酪酪
题目

给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中 最后一个 单词的长度。单词是指仅由字母组成、不包含任何空格字符的最大子字符串。

例:
输入:s = "Hello World"
输出:5
解释:最后一个单词是“World”,长度为5。

方法
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
上一篇 下一篇

猜你喜欢

热点阅读