-
Notifications
You must be signed in to change notification settings - Fork 0
/
32-longestValidParentheses.js
45 lines (38 loc) · 1.05 KB
/
32-longestValidParentheses.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
/**
* @param {string} s
* @return {number}
*/
var longestValidParentheses = function (s) {
let longestValidParenthesesFromIndex = (index) => {
let result = 0;
let count = 0;
let stack = [];
restOfString = s.slice(index);
for (let i = 0; i < restOfString.length; i++) {
let current = restOfString[i];
if (current === "(") {
count++;
stack.push(current);
} else if (current === ")") {
if (stack.length === 0) {
break;
}
count++;
stack.pop();
if (stack.length === 0) {
result = count;
}
}
}
return result;
};
let result = 0;
for (let i = 0; i < s.length; i++) {
let indexResult = longestValidParenthesesFromIndex(i);
if (indexResult > result) {
result = indexResult;
}
}
return result;
};
console.log(longestValidParentheses(")()())"));