C++ concise three line solutions


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

  • 0
    A

    @zyoppy008
    see this one

    class Solution
    {
    public:
    int countSegments(string s)
    {
    stringstream ss(s);
    string temp;
    int count = 0;

        while(getline(ss,temp,' '))
        {
            if(!temp.empty())
                count++;
        }
            
        return count;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.