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 = 0; i < 26; i++){for (int j = i + 1; j < 26; j++){char x = a[i];char y = a[j];string t = "";for (int k = 0; k < n; k++){if (s[k] == x || s[k] == y){t += s[k];}}bool flag = true;for (int f = 0; f + 1 < t.size(); f++){if (t[f] == t[f + 1]){flag = false;break;}}int ts = t.size();if ((flag) && (ts > 1))maxi = max(maxi, ts);}}return maxi;}int main(){int l = 10;string s = "beabeefeab";cout << alternate(s) << "\n";return 0;}
No comments:
Post a Comment