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

Skip to content

Commit ac26cf7

Browse files
authored
Merge pull request #509 from anjola-adeuyi/main
1209. Remove All Adjacent Duplicates in String II - python and JavaScript
2 parents 5cf9e5d + 42c7881 commit ac26cf7

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
/**
2+
* @param {string} s
3+
* @param {number} k
4+
* @return {string}
5+
*/
6+
var removeDuplicates = function (s, k) {
7+
const stack = []; // [char, count];
8+
9+
for (const c of s) {
10+
if (stack.length !== 0 && stack[stack.length - 1][0] === c) {
11+
stack[stack.length - 1][1]++;
12+
} else {
13+
stack.push([c, 1]);
14+
}
15+
16+
if (stack[stack.length - 1][1] === k) {
17+
stack.pop();
18+
}
19+
}
20+
21+
return stack.reduce((res, el) => (res += el[0].repeat(el[1])), '');
22+
};
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution:
2+
def removeDuplicates(self, s: str, k: int) -> str:
3+
stack = [] # [char, count]
4+
5+
for c in s:
6+
if stack and stack[-1][0] == c:
7+
stack[-1][1] += 1
8+
else:
9+
stack.append([c, 1])
10+
11+
if stack[-1][1] == k:
12+
stack.pop()
13+
14+
res = ""
15+
for char, count in stack:
16+
res += (char * count)
17+
18+
return res

0 commit comments

Comments
 (0)