Skip to content

Latest commit

 

History

History
27 lines (22 loc) · 801 Bytes

58.md

File metadata and controls

27 lines (22 loc) · 801 Bytes

思路

  • 标签:从后往前遍历
  • 求最后一个单词,所以从后往前遍历,遇到空格结束,使用变量 length 记录非空格字符的长度。
  • 末尾字符为空格时,如何跳过空格?当末尾字符为空格时,判断长度 length 是否为 0,来跳过空格,继续循环。
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

代码

## Python3
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        length = 0
        for i in range(len(s)):
            if s[len(s) - i - 1] != ' ':
                length += 1
            elif length == 0:
                continue
            else:
                break
        return length