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<Character> st = 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 stackif (st.empty()) {st.push(s.charAt(i));}// if top of stack is same as current element// then we find adjacent duplicates so// remove from stackelse if (st.peek() == s.charAt(i))st.pop();// otherwise we need to put into// the stackelsest.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<char> st;st.push(s[0]);for (int i = 1; i < s.size(); i++){//if stack is empty then we need//to put the current element into//the stackif (st.empty()){st.push(s[i]);}//if top of stack is same as current element//then we find adjacent duplicates so//remove from stackelse if (st.top() == s[i])st.pop();//otherwise we need to put into//the stackelsest.push(s[i]);}string res = "";//now the remaining characters in stack//will we our answerwhile (!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