In: Computer Science
I want this code to be written in c++.
Take a string of length n as an input from the user such that n>=8 and only lower-case letters (a-z) are allowed as valid string characters.
Deleting a letter from the string removes all the occurrences of that letter.
The objective is to find the longest possible string such that
it is left with only two unique letters and no two consecutive
characters
in a string are the same.
If there exist more than one valid longest strings, you need to print any one of those.
The solution should be implemented using pointers
Examples:
Input string: abbdacbdac - > Output string: adada
Input string: cxtdacxdacd - > Output string: cdcdcd
SOLUTION -
#include<bits/stdc++.h>
using namespace std;
int main() {
string s;
int N; //length of string
cin >> N >> s;
vector<char> m;
for(int i = 0; i < N; ++i)
m.push_back(s[i]);
sort(m.begin(), m.end());
m.erase(unique(m.begin(), m.end()), m.end());
int X = m.size();
bool poss = false;
string ans_string;
for(int i = 0; i < X; ++i) {
for(int j = 0; j < X; ++j) {
if(i == j) continue;
char st = m[i], ot = m[j];
int k = 0;
bool curr = true, start = true;
string curr_string;
while(k < N) {
if(s[k] != st && s[k] != ot){
++ k;
continue;
}
if(start) {
if(s[k] != st) {
curr = false;
break;
}
curr_string.push_back(st);
} else {
if(s[k] != ot) {
curr = false;
break;
}
curr_string.push_back(ot);
}
start = !start;
++ k;
}
if(curr && ans_string.size() < curr_string.size())
{
poss = true;
ans_string = curr_string;
}
}
}
if(!poss) cout << "String Not Found";
else
cout << ans_string;
return 0;
}
IF YOU HAVE ANY DOUBT PLEASE COMMENT DOWN BELOW I
WILL SOLVE IT FOR YOU:)
----------------PLEASE RATE THE ANSWER-----------THANK
YOU!!!!!!!!----------