Advertisement
amitsen01ei

StackQueueAssignment.java

Sep 4th, 2023
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.42 KB | Source Code | 0 0
  1. import java.util.*;
  2.  
  3. public class Assignment {
  4.  
  5.     /**
  6.      * Removes adjacent duplicate characters in a given string. The code requires JDK 10+.
  7.      * <p>
  8.      * The function uses a stack to keep track of the characters and removes any adjacent duplicates.
  9.      * </p>
  10.      *
  11.      *<p>
  12.      *Time Complexity: O(N) - where N is the length of the input string.
  13.      *</p>
  14.      *<p>
  15.      *Space Complexity: O(N) - where N is the length of the input string, for storing it in a stack and a StringBuilder.
  16.      *</p>
  17.      *
  18.      * @param s The input string from which to remove duplicates.
  19.      * @return A new string with adjacent duplicates removed.
  20.      *
  21.      */
  22.     private static String removeDuplicates (String s) {
  23.  
  24.         var sArray = s.toCharArray();
  25.  
  26.         var stack = new ArrayDeque<Character>();
  27.  
  28.         for (var ch : sArray) {
  29.             if (stack.peek() != null && stack.peek() == ch) {
  30.                 stack.poll();
  31.             } else {
  32.                 stack.push(ch);
  33.             }
  34.         }
  35.  
  36.         var sb = new StringBuilder();
  37.  
  38.         while (!stack.isEmpty()) {
  39.             sb.append(stack.pollLast());
  40.         }
  41.  
  42.         return sb.toString();
  43.     }
  44.  
  45.     public static void main(String[] args) {
  46.  
  47.         var test1 = "abbaca";
  48.  
  49.         System.out.println(removeDuplicates(test1));
  50.  
  51.  
  52.         var test2 = "azxxzy";
  53.  
  54.         System.out.println(removeDuplicates(test2));
  55.     }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement