leetcode 434.Number of Segments in a String(easy)[分割字符串]

来源:互联网 发布:mongodb 删除数据库 编辑:程序博客网 时间:2024/05/29 15:12

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

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


0 0
原创粉丝点击