[leetcode][434. 字符串中的单词数]

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

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

示例:

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

常见方法,双指针往后跑

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

猜你喜欢

转载自blog.csdn.net/Linger0519/article/details/82819799