Number of Segments in a String
EasyPrompt
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' '.
Approaches
2 approaches with complexity analysis and trade-offs.
This approach leverages the built-in split function available in Java's String class. The idea is to split the string by spaces and then count the number of resulting non-empty parts. It's a very direct and readable solution.
Algorithm
- Trim the leading and trailing whitespace from the input string
s. - Check if the resulting string is empty. If it is, return 0.
- Split the trimmed string by the regex
\s+which matches one or more space characters. - Return the length of the resulting array of strings.
Walkthrough
The core of this method is to first prepare the string and then use the split function.
- Trim the String: The input string
sis first trimmed usings.trim()to remove any leading or trailing whitespace. This is crucial to handle cases like" hello world ", which should result in 2 segments, not more due to leading/trailing spaces. - Handle Empty String: If the trimmed string is empty, it means the original string was either empty or contained only spaces. In this case, there are no segments, so we return 0.
- Split the String: The trimmed string is then split using a regular expression that matches one or more whitespace characters (
"\\s+"). This correctly handles multiple spaces between words. - Return Length: The number of segments is simply the length of the array returned by the
splitmethod.
class Solution { public int countSegments(String s) { // Trim leading and trailing spaces String trimmed = s.trim(); // If the string is empty after trimming, there are no segments if (trimmed.isEmpty()) { return 0; } // Split the string by one or more spaces String[] segments = trimmed.split("\\s+"); // The number of segments is the length of the resulting array return segments.length; }}Complexity
Time
O(N), where N is the length of the string. The `trim()` and `split()` operations both require iterating through the string.
Space
O(N), where N is the length of the string. The `split()` method creates a new array of strings, and the total size of these strings can be proportional to the original string's length in the worst case (e.g., 'a b c d ...').
Trade-offs
Pros
Very concise and easy to read and write.
Leverages well-tested standard library functions.
Cons
Inefficient in terms of space, as it creates an intermediate array of strings.
The overhead of regular expression processing can make it slightly slower than a manual scan for simple cases.
Solutions
Solution
class Solution {public int countSegments(String s) { int ans = 0; for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) { ++ans; } } return ans; }}Video walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.