Skip to content

Commit 18b3040

Browse files
committed
Add Longest Valid Parentheses algorithm(DP)
1 parent 77259b7 commit 18b3040

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
2+
import java.util.Scanner;
3+
4+
/**
5+
* Given a string containing just the characters '(' and ')', find the length of
6+
* the longest valid (well-formed) parentheses substring.
7+
*
8+
*
9+
* @author Libin Yang (https://github.com/yanglbme)
10+
* @since 2018/10/5
11+
*/
12+
13+
public class LongestValidParentheses {
14+
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+
63+
}

0 commit comments

Comments
 (0)