Number of Segments in a String

Number of Segments in a String

Given a string s, return the number of segments in the string. A segment is defined to be a contiguous sequence of non-space characters.

LeetCode Problem - 434

class Solution {
    public int countSegments(String s) {
        // Remove leading and trailing whitespaces, and collapse multiple whitespaces into one
        String str = s.replaceAll("^\\s+", "").replaceAll("\\s+", " ");
        // If the resulting string is empty, return 0
        if (str.isEmpty()) return 0;
        // Split the string by whitespaces to get segments
        String[] segments = str.split(" ");
        // Return the number of segments
        return segments.length;
    }
}