1.问题描述
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
来自 https://leetcode.com/problems/number-of-segments-in-a-string/description/
2.题目分析
计算出字符串的段数,每段之间以空格作为分隔符。这里我们使用两个下标i和j,
首先,i和j移动非空字符,i停止移动,j移动到空字符,完成一段的查找,这是更新i到j,进行下一段的查找,知道结束。对于最后一段是没有空格作为结束符的,因此我们只需判断j移动到字符串尾部了,就算是最后一段了。
3.C++代码
//我的代码:(beats 100%)
int countSegments(string s)
{
int count = 0;
int L = s.length();
int i = 0;
int j = 0;
while (i < L&&j<L)
{
if (s[i] == ' ')
{
i++;
j++;//移动ij到非空字符
}
else
{
if (j == L - 1)//j已经到达字符串尾部
{
count++;
j++;//自加,结束while
}
else
{
if (s[j] != ' ')//移动j到空字符串
j++;
else
{
i = j;//完成一段的查找,更新i
count++;
}
}
}
}
return count;
}
//别人家的代码
int countSegments(string s) {
int count = 0;
bool space = true;
for (int i = 0; i<s.size(); i++) {
if (space == true && s[i] != ' ') {
count++;
space = false;
}
else if (s[i] == ' ') {
space = true;
}
}
return count;
}