打印

【一天一道编程题】之 Number of Segments in a String

[复制链接]
764|6
手机看帖
扫描二维码
随时随地手机跟帖
跳转到指定楼层
楼主
michael_llh|  楼主 | 2016-12-27 11:41 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
本帖最后由 michael_llh 于 2016-12-27 11:42 编辑

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

comes from:

题意分析:
这道题其实很简单,就是统计一个字符串当中有几个子字符串,我们只要遍历一次字符串就可以了。

给出参考代码:(C++

class Solution {
public:
    int countSegments(string s) {
        int n=0;   
        n = s.length();
        char* str= new char(n+1);
        strcpy(str,s.c_str());
        str[n] = '\0';
        int i=0;
        int num = 0;
        while(str!='\0'){
            if(str==' ')
                num++;
            i++;
        }
        return (num+1);
    }
};

上面的解决办法是比较笨重的,而且会有一些问题,比如在下面这个测试案例上面:
另外的参考解决方法:

方法一:
class Solution {public:
    int countSegments(string s) {
        istringstream input(s);
        int count = 0;
        string tmp;
        while (getline(input, tmp, ' ')) if (!tmp.empty()) count++;
        return count;
    }
};

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



相关帖子

沙发
michael_llh|  楼主 | 2016-12-28 13:59 | 只看该作者

使用特权

评论回复
板凳
火山LF| | 2016-12-28 19:48 | 只看该作者
C++用在什么地方的?  目前我只会C

使用特权

评论回复
地板
michael_llh|  楼主 | 2016-12-29 21:20 | 只看该作者
火山LF 发表于 2016-12-28 19:48
C++用在什么地方的?  目前我只会C

挺多方面的,游戏,科学计算,图像处理,嵌入式系统,很多。建议学习

使用特权

评论回复
5
yuanquan12345| | 2016-12-30 10:55 | 只看该作者
michael_llh 发表于 2016-12-29 21:20
挺多方面的,游戏,科学计算,图像处理,嵌入式系统,很多。建议学习

帮忙推荐C++的学习方法及资料,谢谢。

使用特权

评论回复
6
michael_llh|  楼主 | 2016-12-30 11:24 | 只看该作者
yuanquan12345 发表于 2016-12-30 10:55
帮忙推荐C++的学习方法及资料,谢谢。

我分享一个教程给你!
另外书籍的话有很多:
1.C++ primer
2.Effective C++
3.STL源码分析
等等,C++的书籍还是很多的,具体我一下想不起来。
教程:链接:http://pan.baidu.com/s/1mhQYcMc 密码:a41i

使用特权

评论回复
7
yuanquan12345| | 2016-12-30 15:25 | 只看该作者
michael_llh 发表于 2016-12-30 11:24
我分享一个教程给你!
另外书籍的话有很多:
1.C++ primer

谢了。

使用特权

评论回复
发新帖 我要提问
您需要登录后才可以回帖 登录 | 注册

本版积分规则

22

主题

381

帖子

8

粉丝