LeetCode 434. 字符串中的单词数

题目描述: 字符串中的单词数

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

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

示例:

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

解题思路:

        被空格隔开的字符串就是单词,所以出现连续的空格就相当于一个单词, 在判断一下开头和结尾的空格就好了

代码:

class Solution {
public:
    int countSegments(string s) {
        if(s.length() == 0) return 0;
        int ans = 0;
        for(int i = 0; i < s.length(); i ++) {
            if(check(s[i])) {
                ans ++;
                while(i != s.length()&&check(s[i])) i++;
            }
        }
        if(check(s[0])) ans --;
        if(check(s[s.length()-1])) ans --;
        return ans+1;
    }
    
    bool check(char c){
        return c == ' ';
    }
};

你可能感兴趣的:(LeetCode,简单题)