mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
Update 434 solution
This commit is contained in:
@ -1,4 +1,4 @@
|
||||
# [434. Number of Segments in a String](https://leetcode-cn.com/problems/number-of-segments-in-a-string/)
|
||||
# [434. Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/)
|
||||
|
||||
|
||||
## 题目
|
||||
@ -43,3 +43,28 @@ A segment is defined to be a contiguous sequence of non-space characters.
|
||||
## 解题思路
|
||||
|
||||
- 以空格为分割计算元素个数
|
||||
|
||||
## 代码
|
||||
|
||||
```go
|
||||
|
||||
package leetcode
|
||||
|
||||
func countSegments(s string) int {
|
||||
segments := false
|
||||
cnt := 0
|
||||
for _, v := range s {
|
||||
if v == ' ' && segments {
|
||||
segments = false
|
||||
cnt += 1
|
||||
} else if v != ' ' {
|
||||
segments = true
|
||||
}
|
||||
}
|
||||
if segments {
|
||||
cnt++
|
||||
}
|
||||
return cnt
|
||||
}
|
||||
|
||||
```
|
Reference in New Issue
Block a user