Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[LeetCode] 434. Number of Segments in a String #434

Open
grandyang opened this issue May 30, 2019 · 1 comment
Open

[LeetCode] 434. Number of Segments in a String #434

grandyang opened this issue May 30, 2019 · 1 comment

Comments

@grandyang
Copy link
Owner

grandyang commented May 30, 2019

 

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 题目讲解汇总(持续更新中...)

@lld2006
Copy link

lld2006 commented Feb 10, 2020

解法三有些繁琐, 不如将while循环改为
while(iss >> t)++res;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants