LeetCode 434. Number of Segments in a String

来源:互联网 发布:aerial mac 下载 编辑:程序博客网 时间:2024/05/23 23:48

题目

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

思考

通过空格来判断字符串分多少部分,主要是考虑多种特殊情况(比如全空格等)。

答案

c++

class Solution {public:    int countSegments(string s) {        if (s.length() == 0) return 0;        int result = 0;        for (int i = 1; i < s.length(); i++) {            if (s[i] == ' ' && s[i-1] != ' ') {                result++;            }        }        if (s[s.length()-1] != ' ') {            result++;        }        return result;    }};