-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path32.最长有效括号.js
More file actions
49 lines (41 loc) · 832 Bytes
/
32.最长有效括号.js
File metadata and controls
49 lines (41 loc) · 832 Bytes
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
/*
* @lc app=leetcode.cn id=32 lang=javascript
*
* [32] 最长有效括号
*/
// @lc code=start
/**
* @param {string} s
* @return {number}
*/
function isEquals(char1, char2) {
if(char1 === "(" && char2 === ")") {
return true
}
if(char1 === "[" && char2 === "]") {
return true
}
if(char1 === "{" && char2 === "}") {
return true
}
return false
}
var longestValidParentheses = function(s) {
if(s.length <= 1) return 0
const stack = [0]
for(let i = 1; i< s.length; i++) {
if(isEquals(s[stack[stack.length - 1]], s[i])) {
stack.pop()
}else {
stack.push(i)
}
}
stack.unshift(-1)
stack.push(s.length)
let result = 0
for(let i = 0; i< stack.length - 1; i++) {
result = Math.max(stack[i + 1] - stack[i] - 1, result)
}
return result
};
// @lc code=end