File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments