-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path58.最后一个单词的长度.go
54 lines (52 loc) · 1.01 KB
/
58.最后一个单词的长度.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
* @lc app=leetcode.cn id=58 lang=golang
*
* [58] 最后一个单词的长度
*
* https://leetcode-cn.com/problems/length-of-last-word/description/
*
* algorithms
* Easy (29.99%)
* Likes: 107
* Dislikes: 0
* Total Accepted: 28.4K
* Total Submissions: 94.8K
* Testcase Example: '"Hello World"'
*
* 给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。
*
* 如果不存在最后一个单词,请返回 0 。
*
* 说明:一个单词是指由字母组成,但不包含任何空格的字符串。
*
* 示例:
*
* 输入: "Hello World"
* 输出: 5
*
*
*/
func lengthOfLastWord(s string) int {
n := len(s)
if n <= 0 {
return 0
}
index1 := notEmpty(s, n-1)
if index1 == -1 {
return 0
}
index2 := empty(s, index1)
return index1 - index2
}
func notEmpty(s string, from int) int {
for from >= 0 && s[from] == ' ' {
from--
}
return from
}
func empty(s string, from int) int {
for from >= 0 && s[from] != ' ' {
from--
}
return from
}