package leetcode;

/**
 * https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/
 */
public class Problem1047 {
    public String removeDuplicates(String S) {
        String answer = S;
        int i = 0;
        while (i < answer.length() - 1) {
            if (answer.charAt(i) == answer.charAt(i + 1)) {
                answer = answer.substring(0, i) + (i + 2 < answer.length() ? answer.substring(i + 2) : "");
                i--;
                if (i < 0) {
                    i = 0;
                }
            } else {
                i++;
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        Problem1047 prob = new Problem1047();
        System.out.println(prob.removeDuplicates("abbaca")); // ca
        System.out.println(prob.removeDuplicates("aabbaca")); // aca
        System.out.println(prob.removeDuplicates("cabbac")); //
    }
}

@@ -12,16 +12,41 @@
 tcode;%0A%0A
+import java.util.Stack;%0A%0A
 /**%0A * h
@@ -208,23 +208,44 @@
   St
-ring answer = S
+ack%3CCharacter%3E stack = new Stack%3C%3E()
 ;%0A  
@@ -250,16 +250,21 @@
         
+for (
 int i = 
@@ -269,34 +269,14 @@
 = 0;
-%0A        while (i %3C answer
+ i %3C S
 .len
@@ -284,12 +284,13 @@
 th()
- - 1
+; i++
 ) %7B%0A
@@ -309,157 +309,64 @@
 if (
-answer.charAt(i) == answer.charAt(i + 1)) %7B%0A                answer = answer.substring(0, i) + (i + 2 %3C answer.length() ? answer.substring(i + 2) : %22%22
+stack.isEmpty()) %7B%0A                stack.add(S.charAt(i)
 );%0A 
@@ -380,16 +380,16 @@
     
-    i--;
+%7D else %7B
 %0A   
@@ -409,13 +409,35 @@
 if (
-i %3C 0
+stack.peek() == S.charAt(i)
 ) %7B%0A
@@ -456,21 +456,27 @@
         
-i = 0
+stack.pop()
 ;%0A      
@@ -486,30 +486,16 @@
        %7D
-%0A            %7D
  else %7B%0A
@@ -514,357 +514,234 @@
     
-i++;%0A            %7D%0A        %7D%0A        return answer;%0A
+    stack.add(S.charAt(i));%0A                %7D%0A        
     %7D%0A
-%0A
     
-public static void main(String%5B%5D args) %7B%0A        Problem1047 prob = new Problem1047();%0A        System.out.println(prob.removeDuplicates(%22abbaca%22)); // ca%0A        System.out.println(prob.removeDuplicates(%22aabbaca%22)); // aca%0A        System.out.println(prob.removeDuplicates(%22cabbac%22)); //
+    %7D%0A        StringBuilder answer = new StringBuilder();%0A        for (char c : stack) %7B%0A            answer.append(c);%0A        %7D%0A        return answer.toString();
 %0A   

Solve problem 1047