434. Number of Segments in a String
来源: LeetCode 434. Number of Segments in a String
题目描述
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
思路分析
双指针啊双指针又是双指针
代码
class Solution {
public:
int countSegments(string s) {
// 字母数字
int i = 0;
int res = 0;
while(i<s.size() && !canprint(s[i])) ++i;
int j = i;
while(j<s.size()){
while(j<s.size() && canprint(s[j])) ++j;
++res;
i = j;
while(i<s.size() && !canprint(s[i])) ++i;
j = i;
}
return res;
}
bool canprint(char c){
return c > 32;
}
};
算法分析
- 时间复杂度:O(n)
- 空间复杂度:O(1)