首页 > 其他 > 详细

[LeetCode] Number of Segments in a String

时间:2017-10-01 16:38:32      阅读:360      评论:0      收藏:0      [点我收藏+]

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

找出一个字符串中的单词片段,简单来说就是求一个字符串中的单词数,因为每两个单词由一个空格符隔开,所以单词片段数 = 空格符数 + 1,首先在字符串尾添加一个空格,然后遍历字符串返回空格符数即可。

class Solution {
public:
    int countSegments(string s) {
        int res = 0;
        s.push_back( );
        for (int i = 1; i != s.size(); i++)
            if (s[i] ==   && s[i - 1] !=  )
                res++;
        return res;
    }
};
// 3 ms

 

[LeetCode] Number of Segments in a String

原文:http://www.cnblogs.com/immjc/p/7617376.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!