Two Characters

Given a string, remove characters until the string is made up of any two alternating characters. When you choose a character to remove, all instances of that character must be removed. Determine the longest string possible that contains just two alternating letters.

Example:

Input:  l = 10, s = "beabeefeab"
Output: 5

Approach

C++

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

int alternate(string s)
{
    int n = s.size();
    int maxi = 0;
    string a = "abcdefghijklmnopqrstuvwxyz";
    for (int i = 0i < 26i++)
    {
        for (int j = i + 1j < 26j++)
        {
            char x = a[i];
            char y = a[j];
            string t = "";
            for (int k = 0k < nk++)
            {
                if (s[k] == x || s[k] == y)
                {
                    t += s[k];
                }
            }

            bool flag = true;
            for (int f = 0f + 1 < t.size(); f++)
            {
                if (t[f] == t[f + 1])
                {
                    flag = false;
                    break;
                }
            }
            int ts = t.size();
            if ((flag) && (ts > 1))
                maxi = max(maxits);
        }
    }
    return maxi;
}

int main()
{

    int l = 10;
    string s = "beabeefeab";

    cout << alternate(s<< "\n";

    return 0;
}


No comments:

Post a Comment