LeetCode: Longest Valid Parentheses Solution
Approach
Highlight valid parentheses and find max length
Implementation
1function Stack() {2 const stack = []34 this.push = function (el) {5 stack.push(el)6 }78 this.pop = function () {9 return stack.pop()10 }1112 this.peek = function () {13 return stack[stack.length - 1]14 }1516 this.isEmpty = function () {17 return stack.length === 018 }19}2021/**22 * @param {string} s23 * @return {number}24 */25var longestValidParentheses = function (s) {26 const stack = new Stack()27 s = s.split("")28 for (let i = 0; i < s.length; i++) {29 if (s[i] === "(") {30 stack.push(i)31 } else if (s[i] === ")" && s[stack.peek()] === "(") {32 s[stack.peek()] = s[i] = "*"33 stack.pop()34 }35 }36 return Math.max.apply(37 null,38 s39 .join("")40 .split(/[\(\)]/g)41 .filter(Boolean)42 .map(sub => sub.length)43 .concat(0)44 )45}
Comments
Loading comments...
Tags
leetcode
string
dynamic programming
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: Palindrome Linked List
Yeah I skipped the follow-up