题目:
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
翻译:
计算一个字符串中段的个数,其中,段被定义为非空格字符的连续序列。
请注意该字符串不包含任何不可打印的字符。
例子:
输入: "Hello, my name is John" 输出: 5
思路:
首先再字符串 s 的最后加入一个空格 ' ',然后从 s 的开头开始计数,若 s[i]==' ' ,而 s[i-1]!=' ',那么结果count+1。
C++代码(Visual Studio 2017):
#include "stdafx.h" #include <iostream> #include <string> using namespace std; class Solution { public: int countSegments(string s) { s.push_back(' '); int count = 0; if (s.size() <= 0) return 0; for (int i = 1; i < s.size(); i++) { if ((s[i] == ' ') && (s[i - 1] != ' ')) count++; } return count; } }; int main() { Solution s; int result; string str = " "; result = s.countSegments(str); cout << result; return 0; }