434. Number of Segments in a String
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: s = "Hello, my name is John" Output: 5 Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]
Example 2:
Input: s = "Hello" Output: 1
Constraints:
0 <= s.length <= 300
s
consists of lowercase and uppercase English letters, digits, or one of the following characters"!@#$%^&*()_+-=',.:"
.- The only space character in
s
is' '
.
Solutions
Solution 1: String Splitting
We split the string \(\textit{s}\) by spaces and then count the number of non-empty words.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\), where \(n\) is the length of the string \(\textit{s}\).
1 2 3 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
Solution 2: Simulation
We can also directly traverse each character \(\text{s[i]}\) in the string. If \(\text{s[i]}\) is not a space and \(\text{s[i-1]}\) is a space or \(i = 0\), then \(\text{s[i]}\) marks the beginning of a new word, and we increment the answer by one.
After the traversal, we return the answer.
The time complexity is \(O(n)\), where \(n\) is the length of the string \(\textit{s}\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 |
|
1 2 3 4 5 6 7 8 9 10 11 |
|
1 2 3 4 5 6 7 8 9 10 11 12 |
|
1 2 3 4 5 6 7 8 9 |
|
1 2 3 4 5 6 7 8 9 10 |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|