-
Notifications
You must be signed in to change notification settings - Fork 69
/
LVP.java
50 lines (47 loc) Β· 1.33 KB
/
LVP.java
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
public class LVP {
private static int longestValidP(String str) {
int count = 0;
int left = 0;
int right = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (c == '(') {
left++;
}
if (c == ')') {
right++;
}
if (left == right) {
count = Math.max(count, left + right);
}
if (right > left) {
left = right = 0;
}
}
left = right = 0;
for (int i = str.length() - 1; i >= 0; i--) {
char c = str.charAt(i);
if (c == '(') {
left++;
}
if (c == ')') {
right++;
}
if (left == right) {
count = Math.max(count, left + right);
}
if (left > right) {
left = right = 0;
}
}
return count;
}
public static void main(String[] args) {
String str1 = "(()";
System.out.println(longestValidP(str1));
str1 = ")()())";
System.out.println(longestValidP(str1));
str1 = "";
System.out.println(longestValidP(str1));
}
}