434. Number of Segments in a String

Posted wentiliangkaihua

tags:

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

 

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

434. Number of Segments in a String

434. Number of Segments in a String

每天一道LeetCode--434. Number of Segments in a String

434. 求字符串有多少段 Number of Segments in a String

leetcode 434. 字符串中的单词数(Number of Segments in a String)

1104 Sum of Number Segments(二刷)