Leetcode434.Number of Segments in a String字符串中的单词数

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

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

示例:

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

class Solution {
public:
    int countSegments(string s) {
        int len = s.size();
        string temp = "";
        int res = 0;
        for(int i = 0; i < len; i++)
        {
            if(s[i] == ' ')
            {
                if(temp == "")
                    continue;
                else
                {
                    res++;
                    temp = "";
                }
            }
            else
            {
                temp += s[i];
            }

            if(i == len - 1 && temp != "")
                res++;
        }
        return res;
    }
};
原文地址:https://www.cnblogs.com/lMonster81/p/10434094.html