Skip to content

Commit f6e3e64

Browse files
committed
最后一个单词的长度
1 parent 5985790 commit f6e3e64

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

‎SUMMARY.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,7 @@
202202
- [Restore IP Addresses](/algorithm/LeetCode/String/ip.md)
203203
- [Rotate String](/algorithm/LeetCode/String/Rotate-String.md)
204204
- [Valid Palindrome](/algorithm/LeetCode/String/Valid-Palindrome.md)
205+
- [Length of Last Word](/algorithm/LeetCode/String/Length-of-Last-Word.md)
205206

206207
## 设计模式
207208

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
## 一、题目
2+
3+
> Given a string *s* consists of upper/lower-case alphabets and empty space characters `' '`, return the length of last word in the string.
4+
>
5+
> If the last word does not exist, return 0.
6+
>
7+
> **Note:** A word is defined as a character sequence consists of non-space characters only.
8+
>
9+
> For example,
10+
> Given *s* = `"Hello World"`,
11+
> return `5`.
12+
13+
给定一个字符串, 包含大小写字母、空格`' '`,请返回其最后一个单词的长度。
14+
15+
如果不存在最后一个单词,请返回 `0` 。
16+
17+
## 二、解题思路
18+
19+
关键点在于确定最后一个字符串之前的空格,此外还需要考虑末尾空格这一特殊情况。从最后往前扫描。
20+
21+
## 三、解题代码
22+
23+
```java
24+
public class Solution {
25+
public int lengthOfLastWord(String s) {
26+
if (s == null || s.isEmpty()) return 0;
27+
28+
int len = 0;
29+
for (int i = s.length() - 1; i >= 0; i--) {
30+
if (s.charAt(i) == ' ') {
31+
if (len > 0) return len;
32+
} else {
33+
len++;
34+
}
35+
}
36+
37+
return len;
38+
}
39+
}
40+
```
41+

0 commit comments

Comments
 (0)