[LeetCode] 434. Number of Segments in a String (C++)

版权声明:本文为博主原创文章,未经博主允许不得转载。@ceezyyy11 https://blog.csdn.net/ceezyyy11/article/details/89060287

[LeetCode] 434. Number of Segments in a String (C++)

Easy

Share
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 count=0;
        string t;
        istringstream istr(s); // istringstream::istringstream(string str); 
        while(getline(istr,t,' ')) { // istream& getline (istream& is, string& str, char delim);
            if(!t.empty()) { // check for extra spaces
                count++;
                continue;
            }
        }
        return count;
    }
};


// Study Notes:
// (1)	istream& getline (istream& is, string& str, char delim);
// (2)	istream& getline (istream& is, string& str);
// Extracts characters from is and stores them into str until the delimitation character delim is found (or the newline // character, '\n', for (2)).


/**
 * Submission Detail:
 * Runtime: 4 ms, faster than 100.00% of C++ online submissions for Number of Segments in a String.
 * Memory Usage: 8.5 MB, less than 84.75% of C++ online submissions for Number of Segments in a String.
 */

猜你喜欢

转载自blog.csdn.net/ceezyyy11/article/details/89060287