LeetCode: Remove All Adjacent Duplicates In String Solution

Remove all adjacent and equal letters

Approach

Push every character to stack

If the upcoming character is equal to the top character of the stack, pop the stack and skip pushing

Implementation

1/**
2 * @param {string} s
3 * @return {string}
4 */
5var removeDuplicates = function (s) {
6 const stack = []
7
8 for (const char of s) {
9 const top = stack.slice(-1)[0]
10 if (top === char) {
11 stack.pop()
12 } else {
13 stack.push(char)
14 }
15 }
16
17 return stack.join("")
18}

Trick used

Get last element of an array

1array.slice(-1)[0]

Comments

Loading comments...

Tags

leetcode

string

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: Max Consecutive Ones III

Jun 29, 2021

Find the longest contiguos subsequences with K zeros at most

Previous Post

HoningJS

Search Posts