Neutralisation of charges

In a parallel universe, there are not just two charges like positive and negative, but there are 

26 charges represented by  lower 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 s where each si represents a charge, where 0i|s|1.

You need to output size 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 nstring s)
{
    stack<charst;
    for (int i = 0i < ni++)
    {
        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(ns);

    return 0;
}


No comments:

Post a Comment