class Solution:
def countSegments(self, s: str) -> int:
# Split the string by whitespace and filter out empty strings
return len(s.split())
class Solution {
public:
int countSegments(string s) {
int count = 0;
int n = s.size();
for (int i = 0; i < n; ++i) {
if (s[i] != ' ' && (i == 0 || s[i-1] == ' ')) {
count++;
}
}
return count;
}
};
class Solution {
public int countSegments(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i-1) == ' ')) {
count++;
}
}
return count;
}
}
/**
* @param {string} s
* @return {number}
*/
var countSegments = function(s) {
// Split the string by whitespace and filter out empty strings
return s.split(/\s+/).filter(Boolean).length;
};
Given a string s
, count the number of segments in the string. A segment is defined as a contiguous sequence of non-space characters. Segments are separated by one or more spaces.
For example, in the string "Hello, my name is John"
, there are 5 segments: "Hello,"
, "my"
, "name"
, "is"
, and "John"
.
s
(may contain leading, trailing, or multiple consecutive spaces)s
The key to solving this problem is recognizing that segments are simply groups of characters separated by spaces. The naive approach might be to split the string by spaces and count the resulting pieces, but we need to be careful about consecutive spaces, leading, or trailing spaces, which can create empty strings.
For instance, splitting " hello world "
by spaces gives several empty strings. We need to count only the non-empty pieces. Alternatively, we could iterate through the string and count when a new segment starts, which happens when we see a non-space character that follows a space or is at the start of the string.
The optimized approach avoids creating extra strings and works by simply counting segment boundaries as we scan the string.
s
.This approach is efficient because:
Consider the input: s = " Hello world "
count = 0
.'H'
, previous character is a space. This is the start of a segment. Increment count
to 1.'e'
, 'l'
, 'l'
, 'o'
(all are part of the current segment).'w'
, previous character is a space. This is a new segment. Increment count
to 2.'o'
, 'r'
, 'l'
, 'd'
.count = 2
.The optimized approach is preferred for large inputs because it uses minimal additional memory and is straightforward to implement.
To count the number of segments in a string, we scan through the string and count every time we encounter the start of a new segment (a non-space character following a space or at the beginning). This approach is elegant, efficient, and robust against tricky cases like multiple spaces or empty strings. The solution demonstrates the importance of understanding string traversal and boundary detection for simple yet powerful string processing tasks.