forked from TheAlgorithms/JavaScript
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestValidParentheses.js
More file actions
Latest commit
35 lines (28 loc) · 846 Bytes
/
Copy pathLongestValidParentheses.js
File metadata and controls
35 lines (28 loc) · 846 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/*
LeetCode -> https://leetcode.com/problems/longest-valid-parentheses/
Given a string containing just the characters '(' and ')',
find the length of the longest valid (well-formed) parentheses substring.
*/
exportconstlongestValidParentheses=(s)=>{
constn=s.length
conststack=[]
// storing results
constres=newArray(n).fill(-Infinity)
for(leti=0;i<n;i++){
constbracket=s[i]
if(bracket===')'&&s[stack[stack.length-1]]==='('){
res[i]=1
res[stack[stack.length-1]]=1
stack.pop()
}else{
stack.push(i)
}
}
// summing all adjacent valid
for(leti=1;i<n;i++){
res[i]=Math.max(res[i],res[i]+res[i-1])
}
// adding 0 if there are none so it will return 0 instead of -Infinity
res.push(0)
returnMath.max(...res)
}