|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +import java.util.Stack; |
| 4 | + |
| 5 | +/** |
| 6 | + * 1209. Remove All Adjacent Duplicates in String II |
| 7 | + * |
| 8 | + * Given a string s, a k duplicate removal consists of choosing k adjacent and equal |
| 9 | + * letters from s and removing them causing the left and the right side of the deleted substring to concatenate together. |
| 10 | + * We repeatedly make k duplicate removals on s until we no longer can. |
| 11 | + * Return the final string after all such duplicate removals have been made. |
| 12 | + * It is guaranteed that the answer is unique. |
| 13 | + * |
| 14 | + * Example 1: |
| 15 | + * Input: s = "abcd", k = 2 |
| 16 | + * Output: "abcd" |
| 17 | + * Explanation: There's nothing to delete. |
| 18 | + * |
| 19 | + * Example 2: |
| 20 | + * Input: s = "deeedbbcccbdaa", k = 3 |
| 21 | + * Output: "aa" |
| 22 | + * Explanation: |
| 23 | + * First delete "eee" and "ccc", get "ddbbbdaa" |
| 24 | + * Then delete "bbb", get "dddaa" |
| 25 | + * Finally delete "ddd", get "aa" |
| 26 | + * |
| 27 | + * Example 3: |
| 28 | + * Input: s = "pbbcggttciiippooaais", k = 2 |
| 29 | + * Output: "ps" |
| 30 | + * |
| 31 | + * Constraints: |
| 32 | + * 1 <= s.length <= 10^5 |
| 33 | + * 2 <= k <= 10^4 |
| 34 | + * s only contains lower case English letters. |
| 35 | + * */ |
| 36 | +public class _1209 { |
| 37 | + public static class Solution1 { |
| 38 | + public String removeDuplicates(String s, int k) { |
| 39 | + Stack<Character> stack = new Stack<>(); |
| 40 | + char c = s.charAt(0); |
| 41 | + stack.push(c); |
| 42 | + int count = 1; |
| 43 | + for (int i = 1; i < s.length(); i++) { |
| 44 | + if (s.charAt(i) == c) { |
| 45 | + count++; |
| 46 | + stack.push(s.charAt(i)); |
| 47 | + if (count == k) { |
| 48 | + while (!stack.isEmpty() && stack.peek() == c) { |
| 49 | + stack.pop(); |
| 50 | + } |
| 51 | + count = 0; |
| 52 | + if (!stack.isEmpty()) { |
| 53 | + c = stack.peek(); |
| 54 | + while (!stack.isEmpty() && c == stack.peek()) { |
| 55 | + count++; |
| 56 | + stack.pop(); |
| 57 | + } |
| 58 | + int tmp = count; |
| 59 | + while (tmp-- > 0) { |
| 60 | + stack.push(c); |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } else { |
| 65 | + c = s.charAt(i); |
| 66 | + stack.push(s.charAt(i)); |
| 67 | + count = 1; |
| 68 | + } |
| 69 | + } |
| 70 | + StringBuilder sb = new StringBuilder(); |
| 71 | + while (!stack.isEmpty()) { |
| 72 | + sb.append(stack.pop()); |
| 73 | + } |
| 74 | + return sb.reverse().toString(); |
| 75 | + } |
| 76 | + } |
| 77 | +} |
0 commit comments