Skip to content

Commit

Permalink
1209 Remove All Adjacent Duplicate - Javascript
Browse files Browse the repository at this point in the history
  • Loading branch information
anjola-adeuyi committed Jul 17, 2022
1 parent 6c0f646 commit 63cdb37
Showing 1 changed file with 25 additions and 0 deletions.
25 changes: 25 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,25 @@
/**
* @param {string} s
* @param {number} k
* @return {string}
*/
var removeDuplicates = function (s, k) {
const stack = [];

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

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

// Build output of remaining characters
return stack.reduce((res, el) => (res += el[0].repeat(el[1])), '');
};

0 comments on commit 63cdb37

Please sign in to comment.