We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 291bf96 commit cc3e6c6Copy full SHA for cc3e6c6
434 Number of Segments in a String.py
@@ -0,0 +1,34 @@
1
+#!/usr/bin/python3
2
+"""
3
+Count the number of segments in a string, where a segment is defined to be a
4
+contiguous sequence of non-space characters.
5
+
6
+Please note that the string does not contain any non-printable characters.
7
8
9
10
+class Solution:
11
+ def countSegments(self, s):
12
+ """
13
+ I could use split but it may not be the intention of this problem
14
15
+ :type s: str
16
+ :rtype: int
17
18
+ ret = 0
19
+ if not s:
20
+ return ret
21
22
+ # count at start
23
+ if s[0] != " ":
24
+ ret = 1
25
+ prev = s[0]
26
+ for c in s[1:]:
27
+ if c != " " and prev == " ":
28
+ ret += 1
29
+ prev = c
30
31
32
33
+if __name__ == "__main__":
34
+ assert Solution().countSegments("Hello, my name is John") == 5
0 commit comments