0434. Number of Segments in a String (E)

Posted mapoos

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }
}

以上是关于0434. Number of Segments in a String (E)的主要内容,如果未能解决你的问题,请参考以下文章

PAT 1104 Sum of Number Segments

1104 Sum of Number Segments (20)

number-of-segments-in-a-string

Number of Segments in a String

PAT1107:Sum of Number Segments

1104 Sum of Number Segments (20分)(long double)