Skip to content

Commit cc3e6c6

Browse files
committed
434
1 parent 291bf96 commit cc3e6c6

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

434 Number of Segments in a String.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
return ret
31+
32+
33+
if __name__ == "__main__":
34+
assert Solution().countSegments("Hello, my name is John") == 5

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy