LeetCode: Valid Parentheses Solution
Classic stack problemApproach
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} s3 * @return {boolean}4 */5var isValid = function (s) {6 function Stack() {7 const stack = []89 this.push = function (el) {10 stack.push(el)11 }1213 this.pop = function () {14 return stack.pop()15 }1617 this.peek = function () {18 return stack[stack.length - 1]19 }2021 this.isEmpty = function () {22 return stack.length === 023 }24 }2526 const stack = new Stack()27 const isOpen = token => ["(", "[", "{"].includes(token)28 const isCloseOf = tokenA => tokenB =>29 ["()", "[]", "{}"].includes(tokenA + tokenB)3031 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 }4041 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
Implement some linked list methods
Previous Post
LeetCode: Find Pivot Index
2 prefix sums