You are given a string s
, and you need to count the number of segments in the string. A segment is defined to be a contiguous sequence of non-space characters.
Write a function countSegments
that returns the number of segments in the string s
.
Example:
Input: s = "Hello, my name is John"
Output: 5
0
.The approach to solve this problem involves the following steps:
str.split()
will split the string into a list of words, automatically ignoring any number of spaces between words.Using Python’s str.split()
method is efficient because it handles multiple spaces and returns a list of substrings split by the whitespace.
def countSegments(s: str) -> int:
# Split the string by spaces and count the segments
return len(s.split())
# Example usage
s = "Hello, my name is John"
print(countSegments(s)) # Output: 5
The time complexity of the solution is O(n), where n
is the length of the string s
. This is because the split()
method iterates through the entire string once to split the words.
s.split()
: The split()
method splits the string at each sequence of spaces, effectively handling multiple spaces as well as leading and trailing spaces. It returns a list of words.len()
: The len()
function calculates the number of elements in the list returned by split()
, which are the segments of the string.In this way, the function countSegments
counts the number of segments (words) in the given string efficiently.
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?