Leetcode 434 Solution

This article provides solution to leetcode question 434 (number-of-segments-in-a-string)

https://leetcode.com/problems/number-of-segments-in-a-string

Solution

class Solution {
public:
    int countSegments(string s) {
        if (s.size() < 1)
            return 0;

        int cnt = 0;

        for (int i = 1; i < s.length(); i++)
        {
            if (s[i] == ' ' && s[i - 1] != ' ')
                cnt++;
        }

        if (s[s.size() - 1] != ' ')
            cnt++;

        return cnt;
    }
};