-
Notifications
You must be signed in to change notification settings - Fork 0
/
longestValidParenthesis.js
45 lines (44 loc) · 1.39 KB
/
longestValidParenthesis.js
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
36
37
38
39
40
41
42
43
44
45
//leetcode hard 32
var longestValidParentheses = function(s) {
let characterStack=[[")", -1]];
let maxLength=0;
for(let i=0;i<s.length;i++){
if(s[i]=='('){
characterStack.push([s[i], i]);
}else{
if(characterStack[characterStack.length-1][0]=='('){
characterStack.pop();
console.log({characterStack})
if(maxLength<i-characterStack[characterStack.length-1][1]){
maxLength=i-characterStack[characterStack.length-1][1];
}
}else{
characterStack.push([s[i], i]);
}
}
}
return maxLength;
}
var longestValidParenthesess = function(s) {
let indexStack=[-1]
let characterStack=[];
let maxLength=0;
for(let i=0;i<s.length;i++){
if(s[i]=='('){
indexStack.push(i);
characterStack.push(s[i]);
}else{
if(characterStack[characterStack.length-1]=='('){
indexStack.pop();
characterStack.pop();
console.log(indexStack, characterStack)
if(maxLength<i-indexStack[indexStack.length-1]){
maxLength=i-indexStack[indexStack.length-1];
}
}else{
indexStack.push(i);
}
}
}
console.log( maxLength); }
longestValidParentheses( "()()())")