-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlongest-valid-parentheses.js
59 lines (59 loc) · 1.39 KB
/
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
50
51
52
53
54
55
56
57
58
59
/**
* @param {string} s
* @return {number}
*/
var longestValidParentheses = function(s) {
var length = s.length;
if (length <= 0) {
return 0;
}
var strLength = 0;
var count = 0;
var start = 0;
var end = 0;
var maxLength = 0;
var firstLeft = s.indexOf('(');
var lastRight = -1;
for (var i = 0; i < length; i++) {
if (s[i] === ')') {
lastRight = i;
}
}
while (start < length) {
count = 0;
for (var i = start; i < length; i++) {
if (s[i] === '(') {
count ++;
} else {
count --;
}
if (count < 0) {
var tempLength = i - start;
if (tempLength > maxLength) {
maxLength = tempLength;
}
start = i + 1;
break;
}
if (count === 0) {
var tempLength = i - start + 1;
if (tempLength > maxLength) {
maxLength = tempLength;
}
}
}
if (start > lastRight) {
return maxLength;
}
if (count === 0) {
return maxLength;
}
if (count > 0) {
start += 1;
}
if (maxLength >= length - start - 1) {
return maxLength;
}
}
return maxLength;
};