Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class Assignment {
- /**
- * Removes adjacent duplicate characters in a given string. The code requires JDK 10+.
- * <p>
- * The function uses a stack to keep track of the characters and removes any adjacent duplicates.
- * </p>
- *
- *<p>
- *Time Complexity: O(N) - where N is the length of the input string.
- *</p>
- *<p>
- *Space Complexity: O(N) - where N is the length of the input string, for storing it in a stack and a StringBuilder.
- *</p>
- *
- * @param s The input string from which to remove duplicates.
- * @return A new string with adjacent duplicates removed.
- *
- */
- private static String removeDuplicates (String s) {
- var sArray = s.toCharArray();
- var stack = new ArrayDeque<Character>();
- for (var ch : sArray) {
- if (stack.peek() != null && stack.peek() == ch) {
- stack.poll();
- } else {
- stack.push(ch);
- }
- }
- var sb = new StringBuilder();
- while (!stack.isEmpty()) {
- sb.append(stack.pollLast());
- }
- return sb.toString();
- }
- public static void main(String[] args) {
- var test1 = "abbaca";
- System.out.println(removeDuplicates(test1));
- var test2 = "azxxzy";
- System.out.println(removeDuplicates(test2));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement