434. 字符串中的单词数

力扣原题链接(点我直达)

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

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

示例:

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

第一版,这里对单词的定义很不一样。。。

执行用时 :4 ms, 在所有 cpp 提交中击败了65.68%的用户

内存消耗 :8.5 MB, 在所有 cpp 提交中击败了23.30%的用户

int countSegments(string s) {
    int cut = 0;
    string word;
    for (auto& a : s) {
        if (a == ' ' && word != "") {
            cut++;
            //cout << word << endl;
            word = "";
        }
        else if (a == ' ' && word == "") continue;
        else
        {           
            word += a;
        }

    }
    if (word != "") cut++;
    return cut;
}

第二版,利用stringstream来实现

执行用时 :4 ms, 在所有 cpp 提交中击败了65.68%的用户

内存消耗 :8.5 MB, 在所有 cpp 提交中击败了33.50%的用户

是以空格作为分隔符的,很巧妙的流的概念:stringsstream

    int countSegments(string s) {
        string str;
        int count = 0;
        stringstream ss;
        ss << s;
        while (ss >> str) 
            count ++;
        return count;
        
    }