Leetcode 434. Number of Segments in a String
You are 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.
For example:
Input: "Hello, my name is John"
Output: 5
To ensure we understand the requirements correctly, we might ask:
Answering these questions based on common scenarios:
To solve this problem, the strategy generally involves:
Here is the C++ code to solve the problem:
#include <iostream>
#include <string>
class Solution {
public:
int countSegments(std::string s) {
int segmentCount = 0;
int n = s.size();
for (int i = 0; i < n; ++i) {
if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) {
++segmentCount;
}
}
return segmentCount;
}
};
// Example Usage
int main() {
Solution solution;
std::string testString = "Hello, my name is John";
std::cout << "Number of Segments: " << solution.countSegments(testString) << std::endl;
return 0;
}
The time complexity of this solution is (O(n)), where (n) is the length of the string. This is because we perform a single pass over the string to count the segments.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?