[leetcode] 434. Number of Segments in a String

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/w5688414/article/details/90140753

Description

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain any non-printable characters.

Example:

Input:

"Hello, my name is John"

Output:

5

分析

题目的意思是:统计出一个字符串里面的单词。

  • 这道题是easy类型的题目,但是不仔细处理空格的话,就可能AC不全。
  • 思路很简单,从头到尾的遍历,遇见空格之后又遇到字符,说明前面已经遍历了一个单词,就进行+1操作。最后将统计结果返回就行了。

代码

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

参考文献

[LeetCode] Number of Segments in a String 字符串中的分段数量

猜你喜欢

转载自blog.csdn.net/w5688414/article/details/90140753