Number of Segments in a String

You are given a string s, return the number of segments in the string

segment is defined to be a contiguous sequence of non-space characters.

Example :

Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int countSegments(string s)
{
    int cnt = 0;
    if (s.size() == 1)
        if (s[0] != ' ')
            return 1;
    for (int i = 1i < s.size(); i++)
    {

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

int main()
{
    string s = "Hello, my name is John";

    cout << countSegments(s);

    return 0;
}


No comments:

Post a Comment