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.
Example 1:
Input: s = "Hello, my name is John" Output: 5 Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]
Example 2:
Input: s = "Hello" Output: 1
Constraints:
0 <= s.length <= 300
s
consists of lowercase and uppercase English letters, digits, or one of the following characters "!@#$%^&*()_+-=',.:"
.s
is ' '
.When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
The goal is to count how many separate 'words' are in a sentence. The brute force way is to go through each part of the sentence and carefully decide if that part starts a new word.
Here's how the algorithm would work step-by-step:
def count_segments_brute_force(input_string):
segment_count = 0
string_length = len(input_string)
for index in range(string_length):
# Check for non-space character
if input_string[index] != ' ':
# Check if it's the start of a new segment.
if index == 0 or input_string[index - 1] == ' ':
segment_count += 1
return segment_count
The problem asks us to count how many separated groups of characters (segments) are in a string, where segments are separated by spaces. The clever idea is to simply walk through the string and count the number of times a segment begins. A segment begins when a non-space character appears after a space, or at the very start of the string.
Here's how the algorithm would work step-by-step:
def countSegments(input_string):
segment_count = 0
string_length = len(input_string)
for i in range(string_length):
# Check if current char is not space.
if input_string[i] != ' ':
# If it's the first char or preceded by space.
if i == 0 or input_string[i - 1] == ' ':
# Found a new segment.
segment_count += 1
return segment_count
Case | How to Handle |
---|---|
Empty string | Return 0 because there are no segments in an empty string. |
String with only spaces | Return 0 because there are no non-space characters. |
String starting with space(s) | Trim leading spaces or handle the first non-space character correctly in iteration. |
String ending with space(s) | Trim trailing spaces or handle the last non-space character correctly in iteration. |
String with multiple spaces between words | Count a new segment only after encountering a non-space character after a space. |
String with one word and no spaces | Return 1 because there's one segment. |
String with leading, trailing, and multiple internal spaces | Properly handle all space occurrences to count segments correctly. |
Very long string to consider performance. | Iterative solutions should be efficient for long strings, avoid recursive solutions that cause stack overflow. |