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 <= 300sconsists of lowercase and uppercase English letters, digits, or one of the following characters"!@#$%^&*()_+-=',.:".- The only space character in
sis' '.
Solutions
Solution 1: String Splitting
Thinking
Segments are blank-separated. A hand-written scan must handle leading, trailing, and repeated spaces. \(\texttt{split}\) already drops empty pieces, so its length is the answer.
The library walk is a fine first solution.
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
Thinking
Solution 1 allocates the list of words. Counting only, a new segment starts at a non-space whose previous character is a space (or the first index). Extra memory becomes \(O(1)\).
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 | |