其他分享
首页 > 其他分享> > #Leetcode# 434. Number of Segments in a String

#Leetcode# 434. Number of Segments in a String

作者:互联网

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

 

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

代码:

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

  遍历字符串 判断空格之间夹的就是单词了 之前做过 HDU 的单词数 和这个差不多啦

FH

标签:String,int,number,len,++,ans,434,Leetcode,string
来源: https://www.cnblogs.com/zlrrrr/p/10409713.html