Positions of Large Groups

In a string s of lowercase letters, these letters form consecutive groups of the same character.

For example, a string like s = "abbxxxxzyy" has the groups "a""bb""xxxx""z", and "yy".

A group is identified by an interval [start, end], where start and end denote the start and end indices (inclusive) of the group. In the above example, "xxxx" has the interval [3,6].

A group is considered large if it has 3 or more characters.

Return the intervals of every large group sorted in increasing order by start index.

Example:

Input: s = "abbxxxxzzy"
Output: [[3,6]]
Explanation: "xxxx" is the only large group with start index 3 and end index 6.

Approach:

C++

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

vector<vector<int>> largeGroupPositions(string s)
{
    vector<vector<int>> answer;

    for (int i = 1i < s.size(); i++)
        if (s[i] == s[i - 1])
            if (i + 1 < s.size() && s[i + 1] == s[i])
            {
                int j = i + 1;
                while (j < s.size() && s[j] == s[i])
                    {
                        j++;
                    }
                answer.push_back({i - 1j - 1});
                i = j;
            }

    return answer;
}

int main()
{
    string s = "abbxxxxzzy";

    vector<vector<int>> res = largeGroupPositions(s);

    cout << "[";
    for (int i = 0i < res.size(); i++)
    {
        cout << "[";
        for (int j = 0j < res[i].size(); j++)
        {
            cout << res[i][j];
            if (j != res[i].size() - 1)
                cout << ",";
        }
        cout << "]";
        if (i != res.size() - 1)
            cout << ",";
    }
    cout << "]";

    return 0;
}


No comments:

Post a Comment