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

The leetcode link

String one pass implemted in Java

Time complexity: O(n)
Runtime: 3ms

public class Solution {
    public int countSegments(String s) {
        int count = 0;
        for (int i=0; i<s.length(); i++) {
            if (s.charAt(i) != ' ' && (i==0 || s.charAt(i-1) == ' ')){
                count++;
            }
        }
        return count;
    }
}

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))

imgRuntime: 36ms