-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path32 Longest Valid Parentheses.js
More file actions
55 lines (51 loc) · 1.22 KB
/
32 Longest Valid Parentheses.js
File metadata and controls
55 lines (51 loc) · 1.22 KB
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
50
51
52
53
54
55
/**
* Given a string containing just the characters '(' and ')',
* find the length of the longest valid (well-formed) parentheses substring.
* 给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。
*/
/**
* Example 1:
* Input: "(()"
* Output: 2
* Explanation: The longest valid parentheses substring is "()"
*/
/**
*
* @param {array} arr
* @param {number} i
* @param {number} deta
* @param {number} end
* @param {string} char
* @return {number}
*/
const isValid = (arr, i, deta, end, char) => {
let max = 0
let sum = 0
let currentLen = 0
let validLen = 0
for (i; i !== end; i += deta) {
sum += arr[i] === char ? 1 : -1
currentLen += 1
if (sum < 0) {
max = max > validLen ? max : validLen
sum = 0
currentLen = 0
validLen = 0
} else if (sum === 0) {
validLen = currentLen
}
}
return max > validLen ? max : validLen
}
/**
* @param {string} s
* @return {number}
*/
const longestValidParentheses = (s) => {
let parenthes = [...s]
return Math.max(
isValid(parenthes, 0, 1, parenthes.length, '('),
isValid(parenthes, parenthes.length - 1, -1, -1, ')'),
)
}
console.log(longestValidParentheses(')()())'))