Skip to content

Commit 16b1ab7

Browse files
authored
Merge pull request halfrost#172 from gostool/leetcode0434
add: leetcode 0434 solution
2 parents 325e513 + bde069b commit 16b1ab7

File tree

3 files changed

+118
-0
lines changed

3 files changed

+118
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package leetcode
2+
3+
func countSegments(s string) int {
4+
segments := false
5+
cnt := 0
6+
for _, v := range s {
7+
if v == ' ' && segments {
8+
segments = false
9+
cnt += 1
10+
} else if v != ' ' {
11+
segments = true
12+
}
13+
}
14+
if segments {
15+
cnt++
16+
}
17+
return cnt
18+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package leetcode
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
type question434 struct {
9+
para434
10+
ans434
11+
}
12+
13+
// s 是参数
14+
type para434 struct {
15+
s string
16+
}
17+
18+
// ans 是答案
19+
type ans434 struct {
20+
ans int
21+
}
22+
23+
func Test_Problem434(t *testing.T) {
24+
25+
qs := []question434{
26+
27+
{
28+
para434{"Hello, my name is John"},
29+
ans434{5},
30+
},
31+
32+
{
33+
para434{"Hello"},
34+
ans434{1},
35+
},
36+
37+
{
38+
para434{"love live! mu'sic forever"},
39+
ans434{4},
40+
},
41+
42+
{
43+
para434{""},
44+
ans434{0},
45+
},
46+
}
47+
48+
fmt.Printf("------------------------Leetcode Problem 434------------------------\n")
49+
50+
for _, q := range qs {
51+
_, p := q.ans434, q.para434
52+
fmt.Printf("【input】:%v 【output】:%v\n", p, countSegments(p.s))
53+
}
54+
fmt.Printf("\n\n\n")
55+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# [434. Number of Segments in a String](https://leetcode-cn.com/problems/number-of-segments-in-a-string/)
2+
3+
4+
## 题目
5+
6+
You are given a string s, return the number of segments in the string.
7+
8+
A segment is defined to be a contiguous sequence of non-space characters.
9+
10+
**Example 1:**
11+
12+
Input: s = "Hello, my name is John"
13+
Output: 5
14+
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]
15+
16+
**Example 2:**
17+
18+
Input: s = "Hello"
19+
Output: 1
20+
21+
**Example 3:**
22+
23+
Input: s = "love live! mu'sic forever"
24+
Output: 4
25+
26+
**Example 4:**
27+
28+
Input: s = ""
29+
Output: 0
30+
31+
**Constraints**
32+
33+
- 0 <= s.length <= 300
34+
- s consists of lower-case and upper-case English letters, digits or one of the following characters "!@#$%^&*()_+-=',.:".
35+
- The only space character in s is ' '.
36+
37+
## 题目大意
38+
39+
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。
40+
41+
请注意,你可以假定字符串里不包括任何不可打印的字符。
42+
43+
## 解题思路
44+
45+
- 以空格为分割计算元素个数

0 commit comments

Comments
 (0)