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.
1#include <stdio.h>
2#include <string.h>
3
4int countSegments(char *s) {
5 int count = 0;
6 char *token = strtok(s, " ");
7 while (token) {
8 count++;
9 token = strtok(NULL, " ");
10 }
11 return count;
12}
13
14int main() {
15 char str[] = "Hello, my name is John";
16 printf("%d\n", countSegments(str));
17 return 0;
18}
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.
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
This JavaScript solution loops through the string character by character. The loop uses a flag to determine when a sequence of non-space characters starts, thus counting each segment found in the process.