434. Number of Segments in a String
EasySolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to count the number of "segments" in a given string. A segment is defined as a contiguous sequence of non-space characters. This is essentially equivalent to counting the number of words in a sentence, where words are separated by one or more spaces.
Solution
Number of Segments in a String in Python
class Solution:
def countSegments(self, s: str) -> int:
# The built-in s.split() method is the most Pythonic way to solve this.
# It splits the string by any amount of whitespace and automatically
# handles leading/trailing spaces and multiple spaces between words,
# resulting in a list of the segments (non-empty strings).
# For example:
# "Hello, my name is John".split() -> ['Hello,', 'my', 'name', 'is', 'John']
# " ".split() -> []
# The number of segments is simply the length of this resulting list.
return len(s.split())
Number of Segments in a String in Java
class Solution {
public int countSegments(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
// We are looking for the beginning of a segment.
// A segment begins at index i if s.charAt(i) is not a space
// and it's either the first character of the string
// or the character before it was a space.
if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) {
count++;
}
}
return count;
}
}
Number of Segments in a String in C++
class Solution {
public:
int countSegments(string s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
// We are looking for the beginning of a segment.
// A segment begins at index i if s[i] is not a space
// and it's either the first character of the string
// or the character before it was a space.
if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) {
count++;
}
}
return count;
}
};
Number of Segments in a String in TypeScript
function countSegments(s: string): number {
let count = 0;
for (let i = 0; i < s.length; i++) {
// We are looking for the beginning of a segment.
// A segment begins at index i if s[i] is not a space
// and it's either the first character of the string
// or the character before it was a space.
if (s[i] !== ' ' && (i === 0 || s[i - 1] === ' ')) {
count++;
}
}
return count;
};
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.