Easy to understand C++ solution


  • 0
    G

    Keep skip space, if current is not space increase count, and keep skip non-space char.

    class Solution {
    public:
        int countSegments(string s) {
            int count = 0, i = 0;
            while(i < s.size()) {
                while(i < s.size() && s[i] == ' ') ++i;
                if(i < s.size() && s[i] != ' ') ++count;
                while(i < s.size() && s[i] != ' ') ++i;
            }
            return count;
        }
    };
    

Log in to reply
 

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