[LeetCode] 434.Number of Segments in a String
- 题目描述
- 解题思路
- 实验代码
题目描述
Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.
Please note that the string does not contain any non-printable characters.
Example:
Input: “Hello, my name is John”
Output: 5
解题思路
这道题主要在于如何寻找到所需要的“字段”,该字段必须满足:1.它的最后一个字符之后是空格;或者,2.它的最后一个字符就是该字符串的最后一个字符;且,3.它之中的每个字符都不是空格。想到这几个条件之后就能很轻松解决这道题了。
实验代码
class Solution {
public:
int countSegments(string s) {
int sum = 0, l = s.length();
for (int i = 0; i < l; i++)
if (s[i] != ' ' && (i+1 == s.size() || s[i+1] == ' '))
sum++;
return sum;
}
};