![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding the longest valid parentheses JavaScript
Given a string containing just the characters '(' and ')', we find the length of the longest valid (well-formed) parentheses substring.
A set of parentheses qualifies to be a well-formed parentheses, if and only if, for each opening parentheses, it contains a closing parentheses.
For example −
'(())()' is a well-formed parentheses '())' is not a well-formed parentheses '()()()' is a well-formed parentheses
Example
const str = '(())()((('; const longestValidParentheses = (str = '') => { var ts = str.split(''); var stack = [], max = 0; ts.forEach((el, ind) => { if (el == '(') { stack.push(ind); } else { if (stack.length === 0 || ts[stack[stack.length - 1]] == ')'){ stack.push(ind); } else { stack.pop(); }; } }); stack.push(ts.length); stack.splice(0, 0, -1); for (let ind = 0; ind< stack.length - 1; ind++) { let v = stack[ind+1] - stack[ind] - 1; max = Math.max(max, v); }; return max; }; console.log(longestValidParentheses(str));
Output
And the output in the console will be −
6
Advertisements