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

注意审题:一个segment是一段连续的无space的字符串,所以判断字符用空格就够了
public class Solution {
    public int countSegments(String s) {
        if(s == null || s.length() == 0) return 0;
        int count = 0;
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == ' ' && s.charAt(i - 1) != ' ') count++; 
        }
        if (s.charAt(s.length() - 1) != ' ') count++;
        return count;
    }
}
原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13228764.html