This commit is contained in:
youngyangyang04
2020-07-08 09:20:01 +08:00
parent f94ab87f20
commit ef0b0573c1
2 changed files with 30 additions and 0 deletions

View File

@ -0,0 +1,28 @@
## 题目地址
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;
}
};
```