Skip to content

Commit c725d91

Browse files
authored
docs(DP): update LongestValidParentheses.java
1 parent 5ec25c1 commit c725d91

File tree

1 file changed

+46
-50
lines changed

1 file changed

+46
-50
lines changed
Lines changed: 46 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,63 +1,59 @@
1-
21
import java.util.Scanner;
32

43
/**
54
* Given a string containing just the characters '(' and ')', find the length of
65
* the longest valid (well-formed) parentheses substring.
76
*
8-
*
97
* @author Libin Yang (https://github.com/yanglbme)
108
* @since 2018/10/5
119
*/
1210

1311
public class LongestValidParentheses {
1412

15-
public static int getLongestValidParentheses(String s) {
16-
if (s == null || s.length() < 2) {
17-
return 0;
18-
}
19-
char[] chars = s.toCharArray();
20-
int n = chars.length;
21-
int[] res = new int[n];
22-
res[0] = 0;
23-
res[1] = chars[1] == ')' && chars[0] == '(' ? 2 : 0;
24-
25-
int max = res[1];
26-
27-
for (int i = 2; i < n; ++i) {
28-
if (chars[i] == ')') {
29-
if (chars[i - 1] == '(') {
30-
res[i] = res[i - 2] + 2;
31-
} else {
32-
int index = i - res[i - 1] - 1;
33-
if (index >= 0 && chars[index] == '(') {
34-
// ()(())
35-
res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0);
36-
}
37-
}
38-
}
39-
max = Math.max(max, res[i]);
40-
}
41-
42-
return max;
43-
44-
}
45-
46-
public static void main(String[] args) {
47-
Scanner sc = new Scanner(System.in);
48-
49-
while (true) {
50-
String str = sc.nextLine();
51-
if ("quit".equals(str)) {
52-
break;
53-
}
54-
int len = getLongestValidParentheses(str);
55-
System.out.println(len);
56-
57-
}
58-
59-
sc.close();
60-
61-
}
62-
13+
public static int getLongestValidParentheses(String s) {
14+
if (s == null || s.length() < 2) {
15+
return 0;
16+
}
17+
char[] chars = s.toCharArray();
18+
int n = chars.length;
19+
int[] res = new int[n];
20+
res[0] = 0;
21+
res[1] = chars[1] == ')' && chars[0] == '(' ? 2 : 0;
22+
23+
int max = res[1];
24+
25+
for (int i = 2; i < n; ++i) {
26+
if (chars[i] == ')') {
27+
if (chars[i - 1] == '(') {
28+
res[i] = res[i - 2] + 2;
29+
} else {
30+
int index = i - res[i - 1] - 1;
31+
if (index >= 0 && chars[index] == '(') {
32+
// ()(())
33+
res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0);
34+
}
35+
}
36+
}
37+
max = Math.max(max, res[i]);
38+
}
39+
40+
return max;
41+
42+
}
43+
44+
public static void main(String[] args) {
45+
Scanner sc = new Scanner(System.in);
46+
47+
while (true) {
48+
String str = sc.nextLine();
49+
if ("quit".equals(str)) {
50+
break;
51+
}
52+
int len = getLongestValidParentheses(str);
53+
System.out.println(len);
54+
55+
}
56+
57+
sc.close();
58+
}
6359
}

0 commit comments

Comments
 (0)