Description,
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:
Input: "Hello, my name is John"
Output: 5
String one pass implemted in Java
Time complexity: O(n)
Runtime: 3ms
Regex solution in Python.
All you need is to s = s.strip() the input before split.
Then use Regex to solve it.
Note that Python split() can do the multi-space spliting without parameter.
import re
class Solution(object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
s = s.strip()
if not s:
return 0
return len(re.split('\s+', s))
Runtime: 36ms