> For the complete documentation index, see [llms.txt](https://cai-sen-se.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cai-sen-se.gitbook.io/leetcode/1-200/58.-zui-hou-yi-ge-dan-ci-de-chang-du.md).

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

<https://leetcode-cn.com/problems/length-of-last-word/>

## 解法一：py字符处理

```python
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        if not s:
            return 0
        s = s.strip()   #去除首尾空格
        l = s.split(' ')    #按空格切分
        return len(l[-1])   #求最后一项长度
```

## 解法二：

从后往前遍历即可

```python
class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        s = s.strip()    #去除首尾空格
        n = len(s)
        if n == 0:
            return 0
        i = n - 1
        count = 0  #字符计数
        while i >= 0 and s[i] != ' ':    #从后往前，遇到空格即退出
            i -= 1
            count += 1
        return count
```
