File tree Expand file tree Collapse file tree 2 files changed +74
-0
lines changed Expand file tree Collapse file tree 2 files changed +74
-0
lines changed Original file line number Diff line number Diff line change
1
+ > 本文首发于公众号「图解面试算法」,是 [ 图解 LeetCode ] ( < https://github.com/MisterBooo/LeetCodeAnimation > ) 系列文章之一。
2
+ >
3
+ > 个人博客:https://www.zhangxiaoshuai.fun
4
+
5
+ ** 本题选自leetcode第58题,easy难度,目前通过率33.0%**
6
+
7
+ ### 题目描述:
8
+ ``` txt
9
+ 给定一个仅包含大小写字母和空格' '的字符串s,返回其最后一个单词的长度。
10
+ 如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。
11
+ 如果不存在最后一个单词,请返回0。
12
+ 说明:一个单词是指仅由字母组成、不包含任何空格字符的最大子字符串。
13
+
14
+ 示例:
15
+ 输入:"Hello World"
16
+ 输出:5
17
+ ```
18
+
19
+ ### 题目分析:
20
+
21
+ 既然需要求出最后一个单词的长度,那我们直接从** 字符串的末尾** 开始好了;
22
+ 这里末尾有两种情况:有空格和没有空格
23
+
24
+ ```
25
+ (1)有空格:我们从末尾忽略掉空格,然后找到第一个遇见的字符(遇到第一个空格或者遍历完整个字符串为止)
26
+ (2)无空格:直接从末尾往前寻找即可(遇到第一个空格或者遍历完整个字符串为止)
27
+ ```
28
+
29
+ ### 动画gif演示:
30
+
31
+ ![ ] ( ../Animation/0058.gif )
32
+
33
+ ### 代码:
34
+
35
+ ** The first version**
36
+
37
+ ``` java
38
+ public int lengthOfLastWord(String s) {
39
+ if (s. length()== 0 ) {
40
+ return 0 ;
41
+ }
42
+ int index = 0 ;
43
+ int temp = 0 ;
44
+ int p = s. length()- 1 ;
45
+ while ((p- index >= 0 ) && s. charAt(p- index) == 32 ) index++ ;
46
+ for (int i = p- index;i >= 0 ;i-- ) {
47
+ if (s. charAt(i) != 32 ){
48
+ temp++ ;
49
+ continue ;
50
+ }
51
+ break ;
52
+ }
53
+ return temp;
54
+ }
55
+ ```
56
+
57
+ ** 2.代码:**
58
+
59
+ ** The second version**
60
+
61
+ ``` java
62
+ public int lengthOfLastWord(String s) {
63
+ int len = 0 ;
64
+ for (int i = s. length() - 1 ; i >= 0 ; i-- ) {
65
+ if (s. charAt(i) != ' ' ) {
66
+ len++ ;
67
+ } else if (len != 0 ) {
68
+ return len;
69
+ }
70
+ }
71
+ return len;
72
+ }
73
+ ```
74
+
You can’t perform that action at this time.
0 commit comments