mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 23:28:29 +08:00
Update
This commit is contained in:
28
problems/0434.字符串中的单词数.md
Normal file
28
problems/0434.字符串中的单词数.md
Normal 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;
|
||||
}
|
||||
};
|
||||
```
|
Reference in New Issue
Block a user