Steve has a string of lowercase characters in range ascii[‘a’..’z’]. He wants to reduce the string to its shortest length by doing a series of operations. In each operation, he selects a triple of adjacent lowercase letters that match, and he deletes them. For instance, the string aaab could be shortened to b in one operation. Steve’s task is to delete as many characters as possible using this method and print the resulting string. If the final string is empty, print "Empty String" without quotes. Characters can be deleted only if they form a triple and are the same(i.e. from aaaa we can only delete 3 a's and will be left with a single a).
You are required to write a C++ program that implements the above algorithm by using the Stack class.
Example:
Sample Input: aaaabcccdd
Sample Output: abdd
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main(){
cout<<"Enter the string:\n";
string str = "aaaabcccdd";
// cin>>str;
stack<char>stack1;
for(int i=0; i<str.size(); i++){
stack1.push(str.at(i));
}
stack<char>temp;
while(!stack1.empty()){
temp.push(stack1.top());
stack1.pop();
}
stack1 = temp;
cout<<"The contents of the first stack: ";
while(!temp.empty()){
cout<<temp.top()<<" ";
temp.pop();
}
string res = " ";
stack<char>stack3;
while(!stack1.empty()){
char first = stack1.top();
stack1.pop();
char second = stack1.top();
stack1.pop();
if(first==second){
res += first;
}
else{
res += first;
res += second;
}
}
cout<<endl<<res<<endl;
}
Comments
Leave a comment