Advertisement
korobushk

Stackremoveconsecutives

Apr 17th, 2021
923
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.60 KB | None | 0 0
  1.   public static void main(String[] args) {
  2.         String a = "aaaaaabaabccccccc";
  3.         System.out.println(removeConsecutiveDuplicates(a));
  4.     }
  5.  
  6.     public static String removeConsecutiveDuplicates(String str) {
  7.         // Your code here
  8.         Stack<Character> stack = new Stack<>();
  9.         String output = "";
  10.  
  11.         for (int i = 0; i < str.length(); i++) {
  12.             if (stack.isEmpty()||str.charAt(i) != stack.peek()) {
  13.                 stack.push(str.charAt(i));
  14.                 output+=str.charAt(i);
  15.             }
  16.         }
  17.  
  18.         return output;
  19.     }
  20. }
  21.  
  22. //OUTPUT
  23. //ababc
  24.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement