Posts Double Character Trouble
Post
Cancel

Double Character Trouble

PROBLEM DESCRIPTION

You are given a string A. An operation on the string is defined as follows: Remove the first occurrence of the same consecutive characters. eg for a string “abbcd”, the first occurrence of same consecutive characters is “bb”. Therefore the string after this operation will be “acd”. Keep performing this operation on the string until there are no more occurrences of the same consecutive characters and return the final string.

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Solution {
    public String solve(String A) {
        
        Stack<String> s = new Stack<>();

        for(int i=0; i<A.length(); i++){
            
            String x = String.valueOf(A.charAt(i));

            //If current element is same as the top of stack, pop the top element from stack as we found a pair
            if(!s.isEmpty() && x.equals(s.peek())){
                s.pop();
            }else{
                s.push(x);
            }

        }

        StringBuffer sb = new StringBuffer("");
        while(!s.isEmpty()){
            sb.insert(0, s.pop());
        }

        return sb.toString();

    }
}
This post is licensed under CC BY 4.0 by the author.