From e1092756cc69d3ca8a2b1b6b9ec88712d03d9c8e Mon Sep 17 00:00:00 2001 From: 0xff-dev Date: Fri, 4 Apr 2025 19:35:11 +0800 Subject: [PATCH] Add solution and test-cases for problem 434 --- .../README.md | 24 ++++++++----------- .../Solution.go | 23 ++++++++++++++++-- .../Solution_test.go | 13 +++++----- 3 files changed, 37 insertions(+), 23 deletions(-) diff --git a/leetcode/401-500/0434.Number-of-Segments-in-a-String/README.md b/leetcode/401-500/0434.Number-of-Segments-in-a-String/README.md index c752443b7..37eaea0b8 100644 --- a/leetcode/401-500/0434.Number-of-Segments-in-a-String/README.md +++ b/leetcode/401-500/0434.Number-of-Segments-in-a-String/README.md @@ -1,28 +1,24 @@ # [434.Number of Segments in a String][title] -> [!WARNING|style:flat] -> This question is temporarily unanswered if you have good ideas. Welcome to [Create Pull Request PR](https://github.com/kylesliu/awesome-golang-algorithm) - ## Description +Given a string `s`, return the number of segments in the string. + +A **segment** is defined to be a contiguous sequence of **non-space characters**. **Example 1:** ``` -Input: a = "11", b = "1" -Output: "100" +Input: s = "Hello, my name is John" +Output: 5 +Explanation: The five segments are ["Hello,", "my", "name", "is", "John"] ``` -## 题意 -> ... - -## 题解 +**Example 2:** -### 思路1 -> ... -Number of Segments in a String -```go ``` - +Input: s = "Hello" +Output: 1 +``` ## 结语 diff --git a/leetcode/401-500/0434.Number-of-Segments-in-a-String/Solution.go b/leetcode/401-500/0434.Number-of-Segments-in-a-String/Solution.go index d115ccf5e..f94716d3d 100644 --- a/leetcode/401-500/0434.Number-of-Segments-in-a-String/Solution.go +++ b/leetcode/401-500/0434.Number-of-Segments-in-a-String/Solution.go @@ -1,5 +1,24 @@ package Solution -func Solution(x bool) bool { - return x +func Solution(s string) int { + cnt := 0 + start := -1 + end := 0 + for ; end < len(s); end++ { + if s[end] == ' ' { + if start == -1 { + continue + } + cnt++ + start = -1 + continue + } + if start == -1 { + start = end + } + } + if start != -1 { + cnt++ + } + return cnt } diff --git a/leetcode/401-500/0434.Number-of-Segments-in-a-String/Solution_test.go b/leetcode/401-500/0434.Number-of-Segments-in-a-String/Solution_test.go index 14ff50eb4..28d10a2c6 100644 --- a/leetcode/401-500/0434.Number-of-Segments-in-a-String/Solution_test.go +++ b/leetcode/401-500/0434.Number-of-Segments-in-a-String/Solution_test.go @@ -10,12 +10,11 @@ func TestSolution(t *testing.T) { // 测试用例 cases := []struct { name string - inputs bool - expect bool + inputs string + expect int }{ - {"TestCase", true, true}, - {"TestCase", true, true}, - {"TestCase", false, false}, + {"TestCase1", "Hello, my name is John", 5}, + {"TestCase2", "Hello", 1}, } // 开始测试 @@ -30,10 +29,10 @@ func TestSolution(t *testing.T) { } } -// 压力测试 +// 压力测试 func BenchmarkSolution(b *testing.B) { } -// 使用案列 +// 使用案列 func ExampleSolution() { }