434.Number of Segments in a String(String-Easy)
发布日期:2021-06-30 11:46:49 浏览次数:2 分类:技术文章

本文共 991 字,大约阅读时间需要 3 分钟。

转载请注明作者和出处:

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

题目:返回字符串有几个字段。

思路:很简单,空格就是区分字段的标志。

  • 自己写个trim()函数,用于去掉字符串两端的空格;
  • 判断字符串是会否为空,为空返回0,代表有0个字段;
  • 使用空格标志区分字段:上一个字符为空格,当前字符不为空格,字符段计数加一。

Language:cpp

class Solution {public:    //去掉字符串两端的空格    string& trim(string &s) {        if (s.empty()) {            return s;        }        s.erase(0, s.find_first_not_of(" "));        s.erase(s.find_last_not_of(" ") + 1);        return s;    }    int countSegments(string s) {        //字符串为空,返回0        if (trim(s).empty()) {            return 0;        }        int ans = 1;        s = trim(s);           for (int i = 0; i < s.length(); i++) {            //当上一个字符是空格,当前字符不是空格时,则为一个字段            if (s[i-1] == ' ' && s[i] != ' ') {                ans++;            }        }        return ans;    }};

转载地址:https://jackcui.blog.csdn.net/article/details/71786453 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Jetson TX1开发笔记(五):TX1使用OpenCV3.1实时采集视频图像
下一篇:Python3网络爬虫(七):使用Beautiful Soup爬取小说

发表评论

最新留言

感谢大佬
[***.8.128.20]2024年04月12日 05时21分27秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章