码迷,mamicode.com
首页 > 其他好文 > 详细

434. Number of Segments in a String

时间:2020-07-03 10:41:10      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:判断   注意   john   nts   ==   NPU   nbsp   字符   null   

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

标签:判断   注意   john   nts   ==   NPU   nbsp   字符   null   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/13228764.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!