-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlongestValidParentheses.js
More file actions
38 lines (35 loc) · 897 Bytes
/
longestValidParentheses.js
File metadata and controls
38 lines (35 loc) · 897 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
var longestValidParentheses = function(s) {
let maxLength = 0;
// left to right
let left = 0 , right = 0;
for (let itr = 0; itr < s.length; itr++) {
let ch = s[itr];
if (ch == "(") {
left++;
} else {
right++;
}
if(right > left) { // "))))"
left = 0;
right = 0;
} else if (left == right){
maxLength = Math.max(maxLength , (left + right));
}
}
// right to left
for (let itr = s.length - 1; itr >= 0; itr--) {
let ch = s[itr];
if (ch == "(") {
left++;
} else {
right++;
}
if(right < left) { // "(((("
left = 0;
right = 0;
} else if (left == right){
maxLength = Math.max(maxLength , (left + right));
}
}
return maxLength;
};