0434. Number of Segments in a String (E)

Number of Segments in a String (E)

题目

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

题意

计算给定字符串中非空子串的个数

思路

直接遍历处理即可。


代码实现

Java

class Solution {
    public int countSegments(String s) {
        int count = 0;
        int len = 0;
        for (char c : s.toCharArray()) {
            if (c != ' ') {
                len++;
            } else {
                count += len > 0 ? 1 : 0;
                len = 0;
            }
        }
        count += len > 0 ? 1 : 0;
        return count;
    }
}
posted @ 2020-07-14 01:43  墨云黑  阅读(114)  评论(0编辑  收藏  举报