1209. Remove All Adjacent Duplicates in String II

Given a string s, a k duplicate removal consists of choosing k adjacent and equal letters from s and removing them causing the left and the right side of the deleted substring to concatenate together.

We repeatedly make k duplicate removals on s until we no longer can.

Return the final string after all such duplicate removals have been made.

It is guaranteed that the answer is unique.

 

Example 1:

Input: s = "abcd", k = 2
Output: "abcd"
Explanation: There's nothing to delete.

Example 2:

Input: s = "deeedbbcccbdaa", k = 3
Output: "aa"
Explanation: 
First delete "eee" and "ccc", get "ddbbbdaa"
Then delete "bbb", get "dddaa"
Finally delete "ddd", get "aa"

Example 3:

Input: s = "pbbcggttciiippooaais", k = 2
Output: "ps"
分析:
我们把每个letter对应的出现次数放在stack里面,当==k的时候,就pop.
 1 class Solution {
 2     public String removeDuplicates(String s, int k) {
 3         int len = s.length();
 4         Stack<Node> stack = new Stack<>();
 5         for (char c : s.toCharArray()) {
 6             if (!stack.isEmpty() && stack.peek().c == c) {
 7                 stack.peek().count++;
 8             } else {
 9                 stack.push(new Node(c, 1));
10             }
11             if (stack.peek().count == k)
12                 stack.pop();
13         }
14         // build result
15         StringBuilder sb = new StringBuilder();
16         for (Node node : stack) {
17             for (int i = 0; i < node.count; i++) {
18                 sb.append(node.c);
19             }
20         }
21         return sb.toString();
22     }
23 }
24 
25 class Node {
26     char c;
27     int count;
28 
29     public Node(char c, int count) {
30         this.c = c;
31         this.count = count;
32     }
33 }

 

posted @ 2021-03-28 23:49  北叶青藤  阅读(62)  评论(0编辑  收藏  举报