-
Notifications
You must be signed in to change notification settings - Fork 33
/
032-Longest-Valid-Parentheses.js
50 lines (45 loc) · 1.6 KB
/
032-Longest-Valid-Parentheses.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
46
47
48
49
/**
* https://leetcode.com/problems/longest-valid-parentheses/description/
* Difficulty:Hard
*
* Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
* For "(()", the longest valid parentheses substring is "()", which has length = 2.
* Another example is ")()())", where the longest valid parentheses substring is "()()", which has length = 4.
*/
/**
* 使用栈解决
* @param {string} s
* @return {number}
*/
var longestValidParentheses = function (s) {
var stack = [];
for (var i = 0; i < s.length; i++) {
if (s[i] === '(') stack.push(i);
else {
if (stack.length && s[stack[stack.length - 1]] === '(') stack.length--;
else stack.push(i);
}
}
if (!stack.length) return s.length;
var longest = 0;
var end = s.length;
var start = 0;
while (stack.length) {
start = stack[stack.length - 1];
stack.length--;
longest = Math.max(longest, end - start - 1);
end = start;
}
longest = Math.max(longest, end);
return longest;
};
console.log(longestValidParentheses('()'), 2);
console.log(longestValidParentheses('())'), 2);
console.log(longestValidParentheses('(()'), 2);
console.log(longestValidParentheses('))()())((())))'), 6);
console.log(longestValidParentheses('()'), 2);
console.log(longestValidParentheses('('), 0);
console.log(longestValidParentheses(')()()))()()())'), 6);
console.log(longestValidParentheses('()(()'), 2);
console.log(longestValidParentheses('()(()'), 2);
console.log(longestValidParentheses('(()'), 2);