Skip to content

Commit ffb5b5f

Browse files
author
Longerhaha
authored
Merge pull request gzc426#17 from Longerhaha/Longerhaha-patch-5
提交058_(最后一个单词的长度)Length of Last Word至github
2 parents 76a8508 + cfe023c commit ffb5b5f

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
## 058_(最后一个单词的长度)Length of Last Word
2+
## 1 问题描述、输入输出与样例
3+
### 1.1 问题描述
4+
给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。<br>
5+
如果不存在最后一个单词,请返回 0 。
6+
7+
__说明__:一个单词是指由字母组成,但不包含任何空格的字符串。
8+
9+
### 1.2 输入与输出
10+
输入:<br>
11+
* string s:仅包含大小写字母和空格 ' ' 的字符串 s<br>
12+
输出:<br>
13+
* int:最后一个单词的长度
14+
15+
### 1.3 样例
16+
#### 1.3.1 样例1
17+
输入: "Hello World"<br>
18+
输出: 5
19+
20+
#### 1.3.2 样例2
21+
输入: "Hello "<br>
22+
输出: 5
23+
24+
## 2 思路描述与代码
25+
### 2.1 思路描述(单词计数法)
26+
cnt_last_word 为对单词的计数值
27+
```cpp
28+
cnt_last_word = 0;
29+
i = 0;
30+
while( i < len(s) ){
31+
if(s[i] == ' '){
32+
Skip consecutive 0;
33+
//case like 1.3.2
34+
if(s[i] is the last charater of s) return cnt_last_word;
35+
else clear cnt_last_word;
36+
}
37+
else ++cnt_last_word
38+
}
39+
//case like 1.3.1
40+
return cnt_last_word;
41+
```
42+
### 2.2 代码
43+
```cpp
44+
int lengthOfLastWord(string s) {
45+
int s_len = s.size();
46+
int cnt_last_word = 0;
47+
int i = 0;
48+
while( i < s_len ){
49+
if(s[i] == ' ') {
50+
//跳过重复的 ' '
51+
while( i + 1 < s_len && s[i + 1] == ' ') i++;
52+
//如果最后一个也是 ' ',返回连续的 '' 前的单词的长度
53+
if(i == s_len - 1) return cnt_last_word;
54+
else cnt_last_word = 0;
55+
}
56+
//否则加1
57+
else ++cnt_last_word;
58+
++i;
59+
}
60+
return cnt_last_word;
61+
}
62+
```
63+
64+
## 3 思考与拓展
65+
### 3.1 思考
66+
本题较为简单,在增加 1.3.2 样例2 的特殊处理后即可。
67+
#### 3.1.1 其他方法
68+
无。
69+
#### 3.1.2 复杂度分析
70+
方法|空间复杂度|时间复杂度
71+
--- | --- | ---
72+
单词计数法|O(1)|O(n)
73+
#### 3.1.3 难点分析
74+
1. 跳跃重复的' '
75+
2. 需要考虑字符串 s 的尾巴是以一段连续的 ' ' 结尾
76+
### 3.2 拓展
77+
如果给你的数据是链表或者数组数据呢?

0 commit comments

Comments
 (0)