#Leetcode# 434. Number of Segments in a String

https://leetcode.com/problems/number-of-segments-in-a-string/

 

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) {
        s += ' ';
        int len = s.length();
        int ans = 0;
        for(int i = 0; i < len; i ++) {
            if(s[i] == ' ') continue;
            ans ++;
            while(i < len && s[i] != ' ') i ++;
        }
        return ans;
    }
};

  遍历字符串 判断空格之间夹的就是单词了 之前做过 HDU 的单词数 和这个差不多啦

 

posted @ 2019-02-20 22:35  丧心病狂工科女  阅读(111)  评论(0编辑  收藏  举报