Skip to content

Commit d047dda

Browse files
committed
Longest Valid Parentheses solution
1 parent 1e34da5 commit d047dda

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

32-longestValidParentheses.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
var longestValidParentheses = function (s) {
6+
let longestValidParenthesesFromIndex = (index) => {
7+
let result = 0;
8+
let count = 0;
9+
let stack = [];
10+
restOfString = s.slice(index);
11+
12+
for (let i = 0; i < restOfString.length; i++) {
13+
let current = restOfString[i];
14+
if (current === "(") {
15+
count++;
16+
stack.push(current);
17+
} else if (current === ")") {
18+
if (stack.length === 0) {
19+
break;
20+
}
21+
count++;
22+
stack.pop();
23+
if (stack.length === 0) {
24+
result = count;
25+
}
26+
}
27+
}
28+
29+
return result;
30+
};
31+
32+
let result = 0;
33+
34+
for (let i = 0; i < s.length; i++) {
35+
let indexResult = longestValidParenthesesFromIndex(i);
36+
37+
if (indexResult > result) {
38+
result = indexResult;
39+
}
40+
}
41+
42+
return result;
43+
};
44+
45+
console.log(longestValidParentheses(")()())"));

0 commit comments

Comments
 (0)