LeetCode 434——字符串中的单词数

一、题目介绍

统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。

请注意,你可以假定字符串里不包括任何不可打印的字符。

示例:

输入: "Hello, my name is John"
输出: 5
解释: 这里的单词是指连续的不是空格的字符,所以 "Hello," 算作 1 个单词。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-segments-in-a-string
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、解题思路

本题只需对空格字符进行特殊处理即可,详见代码。

三、解题代码

class Solution {
public:
    int countSegments(string s) {
        int cnt = 0;
        int n = s.size();
        int i = 0;
        while(i < n)
        {
            if(s[i] == ' ')
            {
                i++;
                continue;
            }
            while(i < n && s[i] != ' ')
                i++;
            cnt++;
        }
        return cnt;
    }
};

四、解题结果

猜你喜欢

转载自blog.csdn.net/qq_39661206/article/details/113123808