#1209

Remove All Adjacent Duplicates in String II

specialist · 690 · lc medium +30 · verified · 61% accepted · 6,066 likes · top 61%

Description

You have a string s and an integer k. A removal operation selects k consecutive identical characters and deletes them, merging the surrounding parts of the string.

Apply this operation repeatedly until no group of k identical consecutive characters remains.

Return the final string. The answer is guaranteed to be 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"

Code

1
2
3