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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
感谢大佬
[***.8.128.20]2024年04月12日 05时21分27秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
手动安装nginx
2019-04-30
Vue子组件触发父组件事件
2019-04-30
centos8安装docker
2019-04-30
vue自定义指令
2019-04-30
Element ui入门
2019-04-30
weex入门
2019-04-30
linux中使用sed命令注释某特征字符
2019-04-30
CentOS8.0通过yum安装ntp同步时间
2019-04-30
vim安装插件Vundle,NerdTree
2019-04-30
git项目迁移
2019-04-30
从SVN迁移到git仓库
2019-04-30
nacos入门
2019-04-30
consul环境搭建
2019-04-30
lombok的@Accessors注解3个属性说明
2019-04-30
windows 10禁用账户
2019-04-30
U盘设置密码
2019-04-30
JPA事务回滚
2019-04-30
zookeeper图形化的客户端工具
2019-04-30
eureka环境搭建
2019-04-30
consul搭建注册中心
2019-04-30