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.
1using System;
2
3public class Solution {
4 public static int CountSegments(string s) {
5 return s.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).Length;
6 }
7
8 public static void Main(string[] args) {
9 string s = "Hello, my name is John";
10 Console.WriteLine(CountSegments(s));
11 }
12}
In C#, the Split
method with StringSplitOptions.RemoveEmptyEntries
ensures that multiple whitespace separators do not result in empty strings being counted.
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
public class Solution {
public static int CountSegments(string s) {
int count = 0;
bool inSegment = false;
foreach (char c in s) {
if (c != ' ') {
if (!inSegment) {
count++;
inSegment = true;
}
} else {
inSegment = false;
}
}
return count;
}
public static void Main(string[] args) {
string s = "Hello, my name is John";
Console.WriteLine(CountSegments(s));
}
}
In this C# solution, each character is checked to see whether it begins a new segment, and a count is maintained accordingly. The inSegment
boolean is used to track segment changes.