Skip to content

Commit 0229153

Browse files
committed
Add solution #32
1 parent daf94c7 commit 0229153

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@
3737
29|[Divide Two Integers](./0029-divide-two-integers.js)|Medium|
3838
30|[Substring with Concatenation of All Words](./0030-substring-with-concatenation-of-all-words.js)|Hard|
3939
31|[Next Permutation](./0031-next-permutation.js)|Medium|
40+
32|[Longest Valid Parentheses](./0032-longest-valid-parentheses.js)|Hard|
4041
33|[Search in Rotated Sorted Array](./0033-search-in-rotated-sorted-array.js)|Medium|
4142
34|[Find First and Last Position of Element in Sorted Array](./0034-find-first-and-last-position-of-element-in-sorted-array.js)|Medium|
4243
35|[Search Insert Position](./0035-search-insert-position.js)|Easy|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 32. Longest Valid Parentheses
3+
* https://leetcode.com/problems/longest-valid-parentheses/
4+
* Difficulty: Hard
5+
*
6+
* Given a string containing just the characters '(' and ')', return the
7+
* length of the longest valid (well-formed) parentheses substring.
8+
*/
9+
10+
/**
11+
* @param {string} s
12+
* @return {number}
13+
*/
14+
var longestValidParentheses = function(s) {
15+
if (!s.length) {
16+
return 0;
17+
}
18+
19+
const stack = [-1];
20+
let max = 0;
21+
22+
for (let i = 0; i < s.length; i++) {
23+
if (s[i] === '(') {
24+
stack.push(i);
25+
} else {
26+
stack.pop();
27+
if (!stack.length) {
28+
stack.push(i);
29+
} else {
30+
max = Math.max(max, i - stack[stack.length - 1]);
31+
}
32+
}
33+
}
34+
35+
return max;
36+
};

0 commit comments

Comments
 (0)