LeetCode: Remove All Adjacent Duplicates In String II Solution

1/**
2 * @param {string} s
3 * @param {number} k
4 * @return {string}
5 */
6var removeDuplicates = function (s, k) {
7 const stack = []
8 for (let i = 0; i < s.length; i++) {
9 if (s[i] !== s[i - 1]) {
10 stack.push(1)
11 } else {
12 stack[stack.length - 1]++
13 if (stack[stack.length - 1] === k) {
14 stack.pop()
15 s = s.substring(0, i - k + 1) + s.substring(i + 1)
16 i -= k
17 }
18 }
19 }
20 return s
21}

Comments

Loading comments...

Tags

leetcode

stack

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Maximum Ice Cream Bars

HoningJS

Search Posts