LeetCode Number of Segments in a String

LeetCode 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

统计一个字符串中segments的个数,每个segment被至少一个空格隔开,所以不能只单纯统计空格的个数。其实一个segment的特点是以非空格开头,并且前一个字符一定是空格;或者它是第一个segment,开头没有空格。 完整代码如下: [cpp] class Solution { public: int countSegments(string s) { if (s == "")return 0; int ans = 0; for (int i = 0; i < s.size(); i++) { if (s[i] != ‘ ‘) { if (i == 0 || (s[i – 1] == ‘ ‘))ans++; } } return ans; } }; [/cpp] 本代码提交AC,用时0MS。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *