[LeetCode] Number of Segments in a String
阿新 • • 發佈:2017-10-01
ont class span spa count lee log name turn
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