This repository was archived by the owner on Dec 20, 2021. It is now read-only.
File tree Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Expand file tree Collapse file tree 2 files changed +38
-0
lines changed Original file line number Diff line number Diff line change
1
+ # No.434 字符串中的单词数
2
+ <p >统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。</p >
3
+
4
+ <p >请注意,你可以假定字符串里不包括任何不可打印的字符。</p >
5
+
6
+ <p ><strong >示例:</strong ></p >
7
+
8
+ <pre ><strong >输入:</strong > "Hello, my name is John"
9
+ <strong >输出:</strong > 5
10
+ <strong >解释: </strong >这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。
11
+ </pre >
12
+
13
+ # 思路分析
14
+
15
+ 这题考察的有点像状态机。因为需要维护一个前一个字符是不是字母的状态。如果前一个是空格,后一个是字母,就说明开始了一个新单词。
16
+
17
+ # Rust代码
18
+ ``` rust
19
+ # struct Solution ;
20
+ impl Solution {
21
+ pub fn count_segments (s : String ) -> i32 {
22
+ let mut state = 0 ;
23
+ let mut res = 0 ;
24
+ for ch in s . chars () {
25
+ if ch == ' ' {
26
+ state = 0 ;
27
+ } else {
28
+ if state == 0 {
29
+ res += 1 ;
30
+ }
31
+ state = 1 ;
32
+ }
33
+ }
34
+ res
35
+ }
36
+ }
37
+ ```
Original file line number Diff line number Diff line change 6
6
- [ 2021力扣杯秋季编程大赛-战队赛复盘] ( ./special/leetcode-cup-2021-autumn-group.md )
7
7
- [ 2021年] ( ./2021/SUMMARY.md )
8
8
- [ 10月] ( ./2021/10/SUMMARY.md )
9
+ - [ 7日 - 字符串中的单词数] ( ./2021/10/7-No.434.md )
9
10
- [ 6日 - 第三大的数] ( ./2021/10/6-No.414.md )
10
11
- [ 5日 - 窥探迭代器] ( ./2021/10/5-No.284.md )
11
12
- [ 4日 - 密钥格式化] ( ./2021/10/4-No.482.md )
You can’t perform that action at this time.
0 commit comments