Number of Segments in a String

来源:互联网 发布:wifi无网络连接感叹号 编辑:程序博客网 时间:2024/06/03 21:38

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.

class Solution {public:    int countSegments(string s) {        if(s.size()<=0)            return 0;        if(s.size()==1&&s[0]!=' ')            return 1;        int count = 0;        int start = 0, end = s.size() - 1;        while(start < s.size() && s[start]==' ')            ++start;        while(end>=0 && s[end]==' ')            --end;        if(start >= end )            return 0;        while(start < end){            if(s[start]==' '){                ++count;                while(s[start]==' '&&start < end){                    ++start;                }            }            else                ++start;        }        return count + 1;    }};

简洁版本:

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