标签:input 返回 ase segment etc turn lock for table
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
找出一个字符串中的单词片段,简单来说就是求一个字符串中的单词数,因为每两个单词由一个空格符隔开,所以单词片段数 = 空格符数 + 1,首先在字符串尾添加一个空格,然后遍历字符串返回空格符数即可。
class Solution { public: int countSegments(string s) { int res = 0; s.push_back(‘ ‘); for (int i = 1; i != s.size(); i++) if (s[i] == ‘ ‘ && s[i - 1] != ‘ ‘) res++; return res; } }; // 3 ms
[LeetCode] Number of Segments in a String
标签:input 返回 ase segment etc turn lock for table
原文地址:http://www.cnblogs.com/immjc/p/7617376.html