8000 longest-valid-parentheses · malipramod/leetcode-js@0db683b · GitHub
[go: up one dir, main page]

Skip to content

Commit 0db683b

Browse files
committed
longest-valid-parentheses
1 parent f798457 commit 0db683b

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @param {string} s
3+
* @return {number}
4+
*/
5+
var longestValidParentheses = function (s) {
6+
let maxLength = 0;
7+
let stack = [];
8+
stack.push(-1);
9+
for (let i = 0; i < s.length; i++) {
10+
if (s[i] == '(') {
11+
stack.push(i);
12+
} else {
13+
stack.pop();
14+
if (stack.length == 0) {
15+
stack.push(i)
16+
} else {
17+
maxLength = Math.max(maxLength, i - stack[stack.length - 1])
18+
}
19+
}
20+
}
21+
return maxLength;
22+
};
23+
24+
25+
26+
console.log(longestValidParentheses("(()"));
27+
console.log(longestValidParentheses(")()())"));
28+
console.log(longestValidParentheses(")("));
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Longest Valid Parentheses
2+
3+
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
4+
5+
## Example 1
6+
7+
Input: "(()"
8+
9+
Output: 2
10+
11+
Explanation: The longest valid parentheses substring is "()"
12+
13+
## Example 2
14+
15+
Input: ")()())"
16+
17+
Output: 4
18+
19+
Explanation: The longest valid parentheses substring is "()()"
20+
21+
## More info
22+
23+
<https://leetcode.com/problems/longest-valid-parentheses/>

0 commit comments

Comments
 (0)
0