In a parallel universe, there are not just two charges like positive and negative, but there are
charges represented by English alphabets.
Charges have the property of killing each other or in other words neutralizing each other if they are of the same charge and next to each other.
You are given a string where each represents a charge, where .
You need to output of final string followed by string after which no neutralizing is possible.
Example:
Input: n = 12, s= "aaacccbbcccd"
Output: 2
ad
Approach
C++
#include <bits/stdc++.h>using namespace std;void chargeNeutralization(int n, string s){stack<char> st;for (int i = 0; i < n; i++){if (st.size() >= 2){char x = st.top();st.pop();char y = st.top();st.pop();if (x != y){st.push(y);st.push(x);}}st.push(s[i]);}if (st.size() >= 2){char x = st.top();st.pop();char y = st.top();st.pop();if (x != y){st.push(y);st.push(x);}}cout << st.size() << "\n";string str = "";while (!st.empty()){str += st.top();st.pop();}reverse(str.begin(), str.end());cout << str << "\n";}int main(){int n = 12;string s = "aaacccbbcccd";chargeNeutralization(n, s);return 0;}
No comments:
Post a Comment