Skip to content

Commit e109275

Browse files
committed
Add solution and test-cases for problem 434
1 parent f0a9eb1 commit e109275

File tree

3 files changed

+37
-23
lines changed

3 files changed

+37
-23
lines changed

leetcode/401-500/0434.Number-of-Segments-in-a-String/README.md

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,24 @@
11
# [434.Number of Segments in a String][title]
22

3-
> [!WARNING|style:flat]
4-
> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm)
5-
63
## Description
4+
Given a string `s`, return the number of segments in the string.
5+
6+
A **segment** is defined to be a contiguous sequence of **non-space characters**.
77

88
**Example 1:**
99

1010
```
11-
Input: a = "11", b = "1"
12-
Output: "100"
11+
Input: s = "Hello, my name is John"
12+
Output: 5
13+
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]
1314
```
1415

15-
## 题意
16-
> ...
17-
18-
## 题解
16+
**Example 2:**
1917

20-
### 思路1
21-
> ...
22-
Number of Segments in a String
23-
```go
2418
```
25-
19+
Input: s = "Hello"
20+
Output: 1
21+
```
2622

2723
## 结语
2824

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,24 @@
11
package Solution
22

3-
func Solution(x bool) bool {
4-
return x
3+
func Solution(s string) int {
4+
cnt := 0
5+
start := -1
6+
end := 0
7+
for ; end < len(s); end++ {
8+
if s[end] == ' ' {
9+
if start == -1 {
10+
continue
11+
}
12+
cnt++
13+
start = -1
14+
continue
15+
}
16+
if start == -1 {
17+
start = end
18+
}
19+
}
20+
if start != -1 {
21+
cnt++
22+
}
23+
return cnt
524
}

leetcode/401-500/0434.Number-of-Segments-in-a-String/Solution_test.go

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,11 @@ func TestSolution(t *testing.T) {
1010
// 测试用例
1111
cases := []struct {
1212
name string
13-
inputs bool
14-
expect bool
13+
inputs string
14+
expect int
1515
}{
16-
{"TestCase", true, true},
17-
{"TestCase", true, true},
18-
{"TestCase", false, false},
16+
{"TestCase1", "Hello, my name is John", 5},
17+
{"TestCase2", "Hello", 1},
1918
}
2019

2120
// 开始测试
@@ -30,10 +29,10 @@ func TestSolution(t *testing.T) {
3029
}
3130
}
3231

33-
// 压力测试
32+
// 压力测试
3433
func BenchmarkSolution(b *testing.B) {
3534
}
3635

37-
// 使用案列
36+
// 使用案列
3837
func ExampleSolution() {
3938
}

0 commit comments

Comments
 (0)