统计字符串中的单词个数,这里的单词指的是连续的非空字符。
请注意,你可以假定字符串里不包括任何不可打印的字符。
示例:
输入: "Hello, my name is John"
输出: 5

详见:https://leetcode.com/problems/number-of-segments-in-a-string/description/

C++:

方法一:

class Solution {
public:
    int countSegments(string s) {
        int cnt=0;
        for(int i=0;i<s.size();++i)
        {
            if(s[i]!=' '&&(i==0||s[i-1]==' '))
            {
                ++cnt;
            }
        }
        return cnt;
    }
};

 方法二:

class Solution {
public:
    int countSegments(string s) {
        int cnt=0;
        int n=s.size();
        for(int i=0;i<n;++i)
        {
            if(s[i]==' ')
            {
                continue;
            }
            ++cnt;
            while(i<n&&s[i]!=' ')
            {
                ++i;
            }
        }
        return cnt;
    }
};

 参考:https://www.cnblogs.com/grandyang/p/6137386.html

相关文章:

  • 2021-09-21
  • 2021-12-20
  • 2021-10-06
  • 2021-08-28
  • 2021-07-29
  • 2021-05-21
  • 2022-12-23
  • 2021-08-10
猜你喜欢
  • 2022-03-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-23
  • 2021-08-29
  • 2022-12-23
相关资源
相似解决方案