434. Number of Segments in a String

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

Thought

Previous attempts with regular expression to split the string by space or non-word character have got the wrong answers in tests, such as " foo bar", "" and "love live! mu'sic forever".

Consider the following example, the increase the count by 1 if not the space, then moving to the next space ^ position.

↓      ↓  ↓    ↓  ↓
Hello, my name is John
      ^  ^    ^  ^

Solution

public class Solution {
    public int countSegments(String s) {
        int res = 0, n = s.length();
        for (int i = 0; i < n; ++i) {
            if (s.charAt(i) == ' ') continue;
            ++res;
            while (i < n && s.charAt(i) != ' ') ++i;
        }
        return res;
    }
}

results matching ""

    No results matching ""