Leetcode 434 - Number of segments in a string

Note

  • Know how to use reduce: You have to return something everytime!

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.

Example

1
2
3
4
5
6
Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]

Input: s = ""
Output: 0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* @param {string} s
* @return {number}
*/
var countSegments = function(s) {
let segs = s.split(' ');
console.log(segs)
return segs.reduce((acc, cur) => {
if (cur !== '') {
return acc += 1;
}
return acc;
}, 0);
};