Question Two - Number of Segments in a String
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example 1
Input: "Hello, my name is John"
Output: 5
Solution
/**
* @param {string} s
* @return {number}
*/
var countSegments = function(s) {
var sArr = s.trim().split(/\s/);
var result = 0;
var i;
for( i = 0; i < sArr.length; i++){
if(sArr[i].length > 0){
result++;
}
}
return result;
};
Discussion
This problem seemed really straight forward at first. JavaScript has a nice split method for strings that should give me the correct answer if I split by spaces right? - WRONG. An awesome thing about leetcode.com is that they show you the tests that fail when executing your code. I didn't account for spaces at the start and end of the string, or just random spaces in between the words of the string. After some fiddling and testing various scenarios I came up with this solution -
- Use the trim() method to clear any whitespace at the start and end of the string
- Split the string by spaces.
- Splitting the string by spaces still gives an array with a bunch of empty strings if the string had unused white space, so after splitting we need to check the values of the array. If that value's length is greater than 0, increase the number of segments to return by one.
Let's go through the solution with code.
/**
* @param {string} s
* @return {number}
*/
var countSegments = function(s) {
var sArr = s.trim().split(/\s/);
var result = 0;
var i;
};
We create an array (sArr
) of the different segments of the string by timming it and splitting it using a regular expression. Regular expressions are used in programming languages to match particular patterns and the regular expression that represents the space character is \s
. Also, we must place the regular expression between two forward slashes. This one line will solve the first two parts of our psuedocode. We also define the result
or number of segments to be returned as 0
and we define i
to be used in our for loop.
/**
* @param {string} s
* @return {number}
*/
var countSegments = function(s) {
var sArr = s.trim().split(/\s/);
var result = 0;
var i;
for( i = 0; i < sArr.length; i++){
if(sArr[i].length > 0){
result++;
}
}
return result;
};
We use a for
loop to check each item in the array. If it's length is greater 0
i.e. it is not an empty string, then we increase the result by 1
.
After the for loop is done, we return the result
.