Remove All Adjacent Duplicates In String

You are given a string s consisting of lowercase English letters. A duplicate removal consists of choosing two adjacent and equal letters and removing them.

We repeatedly make duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made. It can be proven that the answer is unique.

Example 1:

Input: s = "abbaca"
Output: "ca"
Explanation: 
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move.  The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".

Example 2:

Input: s = "azxxzy"
Output: "ay"

Approach

Java

import java.util.Stack;

public class RemoveAdjacentDuplicates {
    public static void main(String[] args) {

        String s = "abbaca";

        System.out.println(removeDuplicates(s));
    }

    static String removeDuplicates(String s) {
        Stack<Characterst = new Stack<>();
        st.push(s.charAt(0));

        for (int i = 1; i < s.length(); i++) {
            // if stack is empty then we need
            // to put the current element into
            // the stack
            if (st.empty()) {
                st.push(s.charAt(i));
            }

            // if top of stack is same as current element
            // then we find adjacent duplicates so
            // remove from stack
            else if (st.peek() == s.charAt(i))
                st.pop();

            // otherwise we need to put into
            // the stack
            else
                st.push(s.charAt(i));
        }
        String res = "";

        while (!st.empty()) {
            {
                res += st.peek();
                st.pop();
            }

        }
        String ans = "";
        char[] arr = res.toCharArray();

        for (int i = arr.length - 1; i >= 0; i--)
            ans += arr[i];
        return ans;
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

string removeDuplicates(string s)
{
    stack<charst;
    st.push(s[0]);

    for (int i = 1i < s.size(); i++)
    {
        //if stack is empty then we need
        //to put the current element into
        //the stack
        if (st.empty())
        {
            st.push(s[i]);
        }

        //if top of stack is same as current element
        //then we find adjacent duplicates so
        //remove from stack
        else if (st.top() == s[i])
            st.pop();

        //otherwise we need to put into
        //the stack
        else
            st.push(s[i]);
    }
    string res = "";

    //now the remaining characters in stack
    //will we our answer
    while (!st.empty())
    {
        res += st.top();
        st.pop();
    }
    reverse(res.begin(), res.end());

    return res;
}

int main()
{
    string s = "abbaca";

    cout << removeDuplicates(s<< "\n";

    return 0;
}


No comments:

Post a Comment