码迷,mamicode.com
首页 > 其他好文 > 详细

#Leetcode# 434. Number of Segments in a String

时间:2019-02-20 22:51:35      阅读:304      评论:0      收藏:0      [点我收藏+]

标签:string   ring   pac   代码   +=   public   c99   out   code   

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

#Leetcode# 434. Number of Segments in a String

标签:string   ring   pac   代码   +=   public   c99   out   code   

原文地址:https://www.cnblogs.com/zlrrrr/p/10409713.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!