[leetcode]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-printablecharacters.

Example:

Input: "Hello, my name is John"
Output: 5

分析:

返回字符串中单词的个数,单词的定义为不含空格的连续字符。遍历字符串,当前位不为空格并且前一位为空格则个数num+1,另外字符串的首位不是空格num也+1。

class Solution {
public:
    int countSegments(string s) {
        int num = 0;
        for(int i=0; i<s.size(); i++)
        {
            if(s[i] != ' ' && (i == 0 || s[i-1] == ' '))
                num++;      
        }
        return num;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41814716/article/details/85915712