mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-08-06 01:20:05 +08:00
1007 B
1007 B
题目地址
https://leetcode-cn.com/problems/number-of-segments-in-a-string/
思路
可以把问题抽象为 遇到s[i]是空格,s[i+1]不是空格,就统计一个单词, 然后特别处理一下第一个字符不是空格的情况
C++代码
class Solution {
public:
int countSegments(string s) {
int count = 0;
for (int i = 0; i < s.size(); i++) {
// 第一个字符不是空格的情况
if (i == 0 && s[i] != ' ') {
count++;
}
// 只要s[i]是空格,s[i+1]不是空格,count就加1
if (i + 1 < s.size() && s[i] == ' ' && s[i + 1] != ' ') {
count++;
}
}
return count;
}
};
更过算法干货文章持续更新,可以微信搜索「代码随想录」第一时间围观,关注后,回复「Java」「C++」 「python」「简历模板」「数据结构与算法」等等,就可以获得我多年整理的学习资料。