Advertisement
korobushk

RemoveConsecutiveDuplicatesStack

Apr 17th, 2021
1,113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.96 KB | None | 0 0
  1. package removingconsecutiveduplicates2;
  2.  
  3. import java.util.ArrayDeque;
  4. import java.util.Deque;
  5. import java.util.Stack;
  6.  
  7. public class App {
  8.     public static void main(String[] args) {
  9.         String a = "aaabbbcccdddeeefff";
  10.         System.out.println(removePair(a));
  11.     }
  12.  
  13.     public static String removePair(String str) {
  14.  
  15.         Stack<Character> stack = new Stack<>();
  16.         String output = "";
  17.         String rev= "";
  18.         StringBuilder sb = new StringBuilder();
  19.         for (int i = 0; i < str.length(); i++) {
  20.  
  21.             if (stack.isEmpty() || stack.peek() != str.charAt(i)) {
  22.                 stack.push(str.charAt(i));
  23.  
  24.             } else {
  25.  
  26.                 stack.pop();
  27.             }
  28.         }
  29.  
  30.  
  31.         while (!stack.isEmpty()) {
  32.             output += stack.peek();
  33.             stack.pop();
  34.  
  35.         }
  36.         for(int i = output.length()-1;i>=0;i--){
  37.             rev += output.charAt(i);
  38.         }
  39.  
  40.  
  41.         return rev;
  42.     }
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement