前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leetcode-434-Number of Segments in a String

leetcode-434-Number of Segments in a String

作者头像
chenjx85
发布2018-05-22 16:23:47
5270
发布2018-05-22 16:23:47
举报
文章被收录于专栏:chenjx85的技术专栏

题目描述:

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:

代码语言:javascript
复制
Input: "Hello, my name is John"
Output: 5

要完成的函数:

int countSegments(string s) 

说明:

这道题目相当容易。segment定义为不包含空格字符的连续字符串,要求返回一个字符串中有多少这样的segment。

考虑一下边界条件,比如最开始是连续几个空格字符,接下来才是“正经字符”,比如最后以空格结尾,不带空格结尾。

代码如下:

代码语言:javascript
复制
    int countSegments(string s) 
    {
        int i=0,count=0;
        while(i<s.size())
        {
            if(s[i]==' ')
                i++; 
            else
            {
                count++;
                while(s[i]!=' '&&i<s.size())//这里的判断条件也可以换成
                    i++;            //s[i]!=' '&&s[i]!='\0'
            }
        }
        return count;
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-04-21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述:
  • 要完成的函数:
  • 说明:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档