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

0434. Number of Segments in a String (E)

时间:2020-07-14 09:24:30      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:print   tput   lease   ace   inpu   遍历   table   class   output   

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)

标签:print   tput   lease   ace   inpu   遍历   table   class   output   

原文地址:https://www.cnblogs.com/mapoos/p/13296896.html

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