[LeetCode] 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

找出一个字符串中的单词片段,简单来说就是求一个字符串中的单词数,因为每两个单词由一个空格符隔开,所以单词片段数 = 空格符数 + 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

 

posted @ 2017-10-01 16:30  immjc  阅读(100)  评论(0编辑  收藏  举报