[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 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM