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 <= 300s consists of lowercase and uppercase English letters, digits, or one of the following characters "!@#$%^&*()_+-=',.:".s is ' '.One efficient way to determine the number of segments in a string is to utilize its built-in split method, which divides the string into parts based on spaces. The segments will represent contiguous sequences of non-space characters. This approach handles all continuous whitespaces correctly by filtering out empty strings in the resulting list or array.
This C code utilizes the strtok function to tokenize the string s based on spaces. For each token found, the count is incremented. This correctly identifies contiguous groups of non-space characters.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1), using in-place manipulation.
This approach iteratively examines the characters of the string to manually count segments. We increment the segment count every time we encounter the start of a segment: a non-space character that was preceded by a space or the start of the string.
This code manually iterates over each character of the string. The boolean flag inSegment helps track when we are entering a new segment, ensuring we correctly count the number of contiguous non-space character groups.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n), iterating over the string once. Space Complexity: O(1), as no additional storage beyond a few variables is needed.
| Approach | Complexity |
|---|---|
| Splitting Based on Spaces | Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1), using in-place manipulation. |
| Manual Counting with Iteration | Time Complexity: O(n), iterating over the string once. Space Complexity: O(1), as no additional storage beyond a few variables is needed. |
LeetCode 434. Number of Segments in a String Solution Explained - Java • Nick White • 5,203 views views
Watch 9 more video solutions →Practice Number of Segments in a String with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor