Sponsored
Sponsored
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.
Time Complexity: O(n), where n is the length of the string. Space Complexity: O(1), using in-place manipulation.
1public class Solution {
2 public static int countSegments(String s) {
3 String[] segments = s.trim().split("\\s+");
4 return segments[0].isEmpty() ? 0 : segments.length;
5 }
6 public static void main(String[] args) {
7 String s = "Hello, my name is John";
8 System.out.println(countSegments(s));
9 }
10}
In Java, this solution trims the leading and trailing spaces and then splits the string on regex that finds sequences of whitespace characters, returning the number of segments.
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.
Time Complexity: O(n), iterating over the string once. Space Complexity: O(1), as no additional storage beyond a few variables is needed.
1
int countSegments(const std::string &s) {
int count = 0;
bool inSegment = false;
for (char ch : s) {
if (ch != ' ') {
if (!inSegment) {
++count;
inSegment = true;
}
} else {
inSegment = false;
}
}
return count;
}
int main() {
std::string s = "Hello, my name is John";
std::cout << countSegments(s) << std::endl;
return 0;
}
This C++ solution iterates over each character, using a flag inSegment
to determine whether the current character starts a new segment, thereby counting segments manually.