LeetCode: Valid Parentheses Solution

Classic stack problem

Approach

For each token (character) of

s
to stack

  • if it is a closing token for the peak token of stack, pop
  • else push to the stack

The parentheses are valid when stack is empty

Implementation

1/**
2 * @param {string} s
3 * @return {boolean}
4 */
5var isValid = function (s) {
6 function Stack() {
7 const stack = []
8
9 this.push = function (el) {
10 stack.push(el)
11 }
12
13 this.pop = function () {
14 return stack.pop()
15 }
16
17 this.peek = function () {
18 return stack[stack.length - 1]
19 }
20
21 this.isEmpty = function () {
22 return stack.length === 0
23 }
24 }
25
26 const stack = new Stack()
27 const isOpen = token => ["(", "[", "{"].includes(token)
28 const isCloseOf = tokenA => tokenB =>
29 ["()", "[]", "{}"].includes(tokenA + tokenB)
30
31 for (const token of s) {
32 if (isOpen(token)) {
33 stack.push(token)
34 } else if (isCloseOf(stack.peek())(token)) {
35 stack.pop()
36 } else {
37 stack.push(token)
38 }
39 }
40
41 return stack.isEmpty()
42}

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: Design Linked List

Aug 11, 2021

Implement some linked list methods

Previous Post

LeetCode: Find Pivot Index

Aug 9, 2021

2 prefix sums

HoningJS

Search Posts