DIFFICULTY:
Easy
PREREQUISITES:
Adhoc, stacks
PROBLEM:
Bob favourite Data structure is String. He takes a string and decided to reduce string as much as possible by doing a series of operations. In each operation, he selects a pair of adjacent same letters and deletes them.
Note: If the final string is empty, return Empty String.
EXPLANATION:
To get the fully reduced string, we can use a stack. Suppose we are at an ith position of the string. If the character at top of the stack is the same as S[i], we pop the top element of the stack and move to the i+1th position. Otherwise, if the stack is empty or the top element is not equal to S[i], we will push S[i] to top of the stack and then move to i+1th position. Our final answer is all the elements present in the stack from bottom to top. See the setter’s code for implementation details.
TIME COMPLEXITY:
O(N)
SOLUTIONS:
Setter's Solution
#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
#define pb push_back
int main(){
string S;
cin >> S;
vector<char>and;
rep(i,S.length()){
if(ans.size()==0 or S[i]!=ans.back()) ans.pb(S[i]);
else ans.pop_back();
}
if(ans.size()==0) cout<<"Empty String";
else{
for(auto x:ans) cout<<x;
}
}