docs(DP): update LongestValidParentheses.java

This commit is contained in:
Libin Yang 2019-02-24 08:46:51 +08:00 committed by GitHub
parent 5ec25c1670
commit c725d91ecf
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,63 +1,59 @@
import java.util.Scanner; import java.util.Scanner;
/** /**
* Given a string containing just the characters '(' and ')', find the length of * Given a string containing just the characters '(' and ')', find the length of
* the longest valid (well-formed) parentheses substring. * the longest valid (well-formed) parentheses substring.
* *
*
* @author Libin Yang (https://github.com/yanglbme) * @author Libin Yang (https://github.com/yanglbme)
* @since 2018/10/5 * @since 2018/10/5
*/ */
public class LongestValidParentheses { public class LongestValidParentheses {
public static int getLongestValidParentheses(String s) { public static int getLongestValidParentheses(String s) {
if (s == null || s.length() < 2) { if (s == null || s.length() < 2) {
return 0; return 0;
} }
char[] chars = s.toCharArray(); char[] chars = s.toCharArray();
int n = chars.length; int n = chars.length;
int[] res = new int[n]; int[] res = new int[n];
res[0] = 0; res[0] = 0;
res[1] = chars[1] == ')' && chars[0] == '(' ? 2 : 0; res[1] = chars[1] == ')' && chars[0] == '(' ? 2 : 0;
int max = res[1]; int max = res[1];
for (int i = 2; i < n; ++i) { for (int i = 2; i < n; ++i) {
if (chars[i] == ')') { if (chars[i] == ')') {
if (chars[i - 1] == '(') { if (chars[i - 1] == '(') {
res[i] = res[i - 2] + 2; res[i] = res[i - 2] + 2;
} else { } else {
int index = i - res[i - 1] - 1; int index = i - res[i - 1] - 1;
if (index >= 0 && chars[index] == '(') { if (index >= 0 && chars[index] == '(') {
// ()(()) // ()(())
res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0); res[i] = res[i - 1] + 2 + (index - 1 >= 0 ? res[index - 1] : 0);
} }
} }
} }
max = Math.max(max, res[i]); max = Math.max(max, res[i]);
} }
return max; return max;
} }
public static void main(String[] args) { public static void main(String[] args) {
Scanner sc = new Scanner(System.in); Scanner sc = new Scanner(System.in);
while (true) { while (true) {
String str = sc.nextLine(); String str = sc.nextLine();
if ("quit".equals(str)) { if ("quit".equals(str)) {
break; break;
} }
int len = getLongestValidParentheses(str); int len = getLongestValidParentheses(str);
System.out.println(len); System.out.println(len);
} }
sc.close();
}
sc.close();
}
} }