[leetcode-434-Number of Segments in a String]

时间:2021-12-16 06:19:57

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

思路:

从头到尾遍历,如果是空格,直接跳过。

非空格字符都遍历完后,segment++。

int countSegments(string s)
{
int seg = ;
int len = s.length();
for (int i = ; i < len;)
{
while (i < len && s[i] == ' ')i++;//去掉空格
if (i>=len) break;
while (i < len && s[i] != ' ')i++;
seg++;
} return seg;
}