[LeetCode] 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
 
这道题跟之前那道Reverse Words in a String有些类似,不过比那题要简单一些,因为不用翻转单词,只要统计出单词的数量即可。那么我们的做法是遍历字符串,遇到空格直接跳过,如果不是空格,则计数器加1,然后用个while循环找到下一个空格的位置,这样就遍历完了一个单词,再重复上面的操作直至结束,就能得到正确结果:
 
解法一:
class Solution {
public:
    int countSegments(string s) {
        int res = 0, n = s.size();
        for (int i = 0; i < n; ++i) {
            if (s[i] == ' ') continue;
            ++res;
            while (i < n && s[i] != ' ') ++i;
        }
        return res;
    }
};

 

下面这种方法是统计单词开头的第一个字符,因为每个单词的第一个字符前面一个字符一定是空格,利用这个特性也可以统计单词的个数:

 

解法二:

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

 

下面这种方法用到了C++的字符串流操作,利用getline函数取出每两个空格符之间的字符串,由于多个空格符可能连在一起,所以有可能取出空字符串,我们要判断一下,如果取出的是非空字符串我们才累加计数器,参见代码如下:

 

解法三:

class Solution {
public:
    int countSegments(string s) {
        int res = 0;
        istringstream is(s);
        string t = "";
        while (getline(is, t, ' ')) {
            if (t.empty()) continue;
            ++res;
        }
        return res;
    }
};

 

类似题目:

Reverse Words in a String

 

参考资料:

https://discuss.leetcode.com/topic/70775/c-istringstream-try

https://discuss.leetcode.com/topic/70642/clean-java-solution-o-n

https://discuss.leetcode.com/topic/70656/ac-solution-java-with-trim-and-split

 

LeetCode All in One 题目讲解汇总(持续更新中...)

posted @ 2016-12-06 14:07  Grandyang  阅读(5341)  评论(3编辑  收藏  举报
Fork me on GitHub