Thanks to visit codestin.com
Credit goes to github.com

Skip to content

1209. Remove All Adjacent Duplicates in String II - python and JavaScript #509

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions javascript/1209-Remove-All-Adjacent-Duplicates-in-String-II.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* @param {string} s
* @param {number} k
* @return {string}
*/
var removeDuplicates = function (s, k) {
const stack = []; // [char, count];

for (const c of s) {
if (stack.length !== 0 && stack[stack.length - 1][0] === c) {
stack[stack.length - 1][1]++;
} else {
stack.push([c, 1]);
}

if (stack[stack.length - 1][1] === k) {
stack.pop();
}
}

return stack.reduce((res, el) => (res += el[0].repeat(el[1])), '');
};
18 changes: 18 additions & 0 deletions python/1209-Remove-All-Adjacent-Duplicates-in-String-II.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
class Solution:
def removeDuplicates(self, s: str, k: int) -> str:
stack = [] # [char, count]

for c in s:
if stack and stack[-1][0] == c:
stack[-1][1] += 1
else:
stack.append([c, 1])

if stack[-1][1] == k:
stack.pop()

res = ""
for char, count in stack:
res += (char * count)

return res