LeetCode/solutions/434. Number of Segments in a String.md
2019-09-13 23:08:41 +08:00

22 lines
727 B
Markdown
Raw Permalink 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.

# [434. Number of Segments in a String](https://leetcode.com/problems/number-of-segments-in-a-string/description/)
# 思路
计算一个字符串被空格分成了多少部分。
从头至尾遍历字符串用tag标记当前字符的前一个字符是否是空格若tag=1则前面是空格否则不是。若当前字符不是空格且tag==1则count应该加1。
# C++
```C++
class Solution {
public:
int countSegments(string s) {
int tag = 1, res = 0;
for(int p = 0; p < s.size(); p++){
if(s[p] == ' ') tag = 1;
else if(tag == 1){ // 当前字符不是空格且tag==1
res++;
tag = 0;
}
}
return res;
}
};
```