LC058

package
v0.0.0-...-b071cee Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 9, 2023 License: GPL-3.0 Imports: 0 Imported by: 0

README

最后一个单词的长度

1.题目描述

给你一个字符串 s,由若干单词组成,单词前后用一些空格字符隔开。返回字符串中最后一个单词的长度。

单词是指仅由字母组成、不包含任何空格字符的最大子字符串。

2. 示例

提示:

1 <= s.length <= 104
s 仅有英文字母和空格 ' ' 组成
s 中至少存在一个单词

示例 1:

输入:s = "Hello World"
输出:5

示例 2:

输入:s = "   fly me   to   the moon  "
输出:4

示例 3:

输入:s = "luffy is still joyboy"
输出:6

3. 解题

1.可以反向遍历字符串,寻找最后一个单词并计算其长度。
2.由于字符串中至少存在一个单词,因此字符串中一定有字母。首先通过过滤掉尾部的空格找到字符串中的最后一个字母。
3.从最后一个字母开始继续反向遍历字符串,直到遇到空格或者到达字符串的起始位置。遍历到的每个字母都是最后一个单词中的字母,因此遍历到的字母数量即为最后一个单词的长度。

Documentation

The Go Gopher

There is no documentation for this package.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL