leetcode-master/problems/0434.字符串中的单词数.md

31 lines
1007 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 题目地址
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」「简历模板」「数据结构与算法」等等就可以获得我多年整理的学习资料。