Skip to content

Commit 97007b8

Browse files
committed
Number of segments in a string.
1 parent c43f222 commit 97007b8

File tree

4 files changed

+61
-0
lines changed

4 files changed

+61
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/**
2+
Given a string s, return the number of segments in the string.
3+
4+
A segment is defined to be a contiguous sequence of non-space characters.
5+
6+
 
7+
8+
Example 1:
9+
Input: s = "Hello, my name is John"
10+
Output: 5
11+
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]
12+
13+
Example 2:
14+
Input: s = "Hello"
15+
Output: 1
16+
 
17+
18+
Constraints:
19+
- 0 <= s.length <= 300
20+
- s consists of lowercase and uppercase English letters, digits, or one of the following characters "!@#$%^&*()_+-=',.:".
21+
- The only space character in s is ' '.
22+
*/
23+
class Solution {
24+
func countSegments(_ s: String) -> Int {
25+
guard !s.isEmpty else { return 0 }
26+
var start = 0
27+
var end = 0
28+
var count = 0
29+
for c in s {
30+
if c != " " {
31+
end += 1
32+
} else {
33+
if end > start {
34+
count += 1
35+
start = 0
36+
end = 0
37+
}
38+
}
39+
}
40+
if end > start {
41+
count += 1
42+
}
43+
return count
44+
}
45+
}
46+
47+
let s = Solution()
48+
let r = s.countSegments(" ")
49+
print(r)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios' buildActiveScheme='true' importAppTypes='true'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

Easy/434.Number of Segments in a String.playground/playground.xcworkspace/contents.xcworkspacedata

Lines changed: 7 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@
8787
83. [Fizz Buzz](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/409.Fizz%20Buzz.playground/Contents.swift)
8888
84. [Third Maximum Number](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/414.Third%20Maximum%20Number.playground/Contents.swift)
8989
85. [Add Strings](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/415.Add%20Strings.playground/Contents.swift)
90+
86. [Number of Segments in a String](https://github.com/recherst/leetcode-algtorithm/blob/main/Easy/434.Number%20of%20Segments%20in%20a%20String.playground/Contents.swift)
9091

9192
#### Medium
9293

0 commit comments

Comments
 (0)