Given a string str consisting of only two characters 'a' and 'b'. You need to find the minimum steps required to make the string empty by removing consecutive a's and b's
Question: Given a string str consisting of only two characters 'a' and 'b'. You need to find the minimum steps required to make the string empty by removing consecutive a's and b's
My CODE(Shows RUNTIME ERROR(take more time than expected)):
#include <iostream>
#include <string>
using namespace std;
int ForB(string str,int sizeA,int countA=0,int i=0){
/*if(i==sizeB){
return countB;
}*/
while(i!=sizeA){
if (str[i]=='b' || str[i]=='B'){
if(i!=sizeA-1){
str[i]='X';}
else if (i==sizeA-1){
str[i]='X';
countA++;
}
i++;}
else if((str[i]!='a'||str[i]!='A')&&(/*str[i-1]=='a'||*/ str[i-1]=='X')){
countA++; i++;
}
}
return countA;
}
int ForA(string str,int sizeA,int countA=0,int i=0){
/* if(i==sizeA){
return countA;
}*/
while(i!=sizeA){
if (str[i]=='a' || str[i]=='A'){
if(i!=sizeA-1){
str[i]='X';}
else if (i==sizeA-1){
str[i]='X';
countA++;
}
i++;}
else if((str[i]!='b'||str[i]!='B')&&(/*str[i-1]=='a'||*/ str[i-1]=='X')){
countA++; i++;
}
}
return countA;
}
int minSteps(string str) {
int A=ForA(str,str.length());
int B=ForB(str,str.length());
if(A<B){
return A+1;
}
else{
return B+1;
}
}
int main(){
cout<<"Enter the string count";
int t;
cin>>t;
while(t--){
cout<<"Enter The a and b string";
string str;
cin>>str;
cout<<minSteps(str)<<"this is the ans"<<endl;
}
}
Comments
Post a Comment