Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit b37adb0

Browse files
Create number-of-Segments-in-a-String.js
1 parent 54f4585 commit b37adb0

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
3+
434. Number of Segments in a String
4+
https://leetcode.com/problems/number-of-segments-in-a-string/description/
5+
6+
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
7+
8+
Please note that the string does not contain any non-printable characters.
9+
10+
Example:
11+
12+
Input: "Hello, my name is John"
13+
Output: 5
14+
*/
15+
16+
/**
17+
* @param {string} s
18+
* @return {number}
19+
*/
20+
var countSegments = function(s) {
21+
var count = 0;
22+
var i = 0;
23+
24+
while(i < s.length) {
25+
if(s[i] !== " ") {
26+
count++;
27+
while(i < s.length && s[i] !== " ") {
28+
i++;
29+
}
30+
}
31+
i++;
32+
}
33+
34+
return count;
35+
};
36+
37+
38+
function main() {
39+
console.log(countSegments(" "));
40+
console.log(countSegments(" "));
41+
console.log(countSegments("ab cd ef"));
42+
console.log(countSegments(" ab cd ef"));
43+
console.log(countSegments("ab cd ef "));
44+
console.log(countSegments(" ab cd ef "));
45+
}
46+
47+
module.exports.main = main

0 commit comments

Comments
 (0)