Remove All Adjacent Duplicates In String

4 years ago Lalit Bhagtani 0

Problem Statement

You have given a string (lowercase letters only), write a program to remove all the adjacent duplicate letters from the given string and return the modified string. The return string should not contain any adjacent duplicate letters.

Example 

Remove All Adjacent Duplicates

Input :- "abbaca"
Output :- "ca"
Input :- "dabbacabbace"
Output :- "de"

Solution

The Stack data structure can be used to solve this problem, following are the steps :-

  1. Create the character array from the input String.
  2. Iterate through the character array and at each iteration, check if the stack is non-empty and its top element is equal to the current element.
  3. If yes, then pop the top element of the stack.
  4. If no, then push the current element on the top of the stack.

Program

import java.util.Stack;

public class Main {

	public static void main(String[] args) {		
		Main main = new Main();
		String result = main.removeDuplicates("dabbacabbace");
		System.out.print(result);										
	}  
	
	/* Solution */    
	public String removeDuplicates(String S) {
        Stack<Character> stack = new Stack<>();
        char[] array = S.toCharArray();
        for(int i=0; i<array.length; i++){
            if(stack.size() > 0 && array[i] == stack.peek()){
                stack.pop();
            }else {
                stack.push(array[i]);
            }
        }
        
        StringBuilder sb = new StringBuilder();
        while(stack.size() >0){
            sb.insert(0, stack.pop());
        }
        return sb.toString();
    }
}

Result

de 

Similar Post

  1. Backspace String Compare
  2. Valid Parentheses
  3. Next Greater Element

That’s all for Remove All Adjacent Duplicates In String in Java, If you liked it, please share your thoughts in a comments section and share it with others too.