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;
    }
}
复制代码

 

posted @   Schwifty  阅读(116)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示