Number of Segements in a String

Problem

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

Solution

Split and Regex: O(1)

public class Solution {
    public int countSegments(String s) {
        if (s == null) return 0;
        //We need to add a character at the beginning 
        //Because " a b" will split into [" ", "a", "b"]
        return ("* " + s).split("\\s+").length - 1; 
    }
}

Regular Iteration: O(n)

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

Analysis

A very straightforward problem
Notice that how we use split() method correctly

results matching ""

    No results matching ""