leetcode 434. 字符串中的单词数(Number of Segments in a String)

题目描述:

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

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

示例:

    输入: "Hello, my name is John"
    输出: 5

解法:

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

猜你喜欢

转载自www.cnblogs.com/zhanzq/p/10579878.html