# 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

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}/**2 * @param {string} s3 * @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 === 023    }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}```

leetcode

string

stack

Aug 11, 2021

## Previous Post

LeetCode: Find Pivot Index

Aug 9, 2021

2 prefix sums

Search Posts