1、已知一个字符串都是由左括号(和右括号)组成,判断该字符串是否是有效的括号组合。
例子:
有效的括号组合:()(),(()),(()())
2、题目进阶:
例子:
有效的括号组合:()(),(()),(()())
无效的括号组合:(,()),((),()(()
思路:略
2、题目进阶:
已知一个字符串都是由左括号(和右括号)组成,返回最长有效括号子串的长度。
进阶思路:
用一个数组dp来记录以当前字符结尾的最长有效括号子串的长度。遍历整个数组,找出dp的最大值。
比如:“()()()”,则dp=[0 2 0 4 0 6]
考虑位置i:
1. 当当前字符为“(”,必然无效,所以dp[i]=0;
2. 当当前字符为“)”时,则看以字i-1结尾的有效字符串的前一个字符,是否与当前的匹配,该字符的下标记为pre,如果是“(”的话,则匹配,那么以i结尾的有效字符串的长度等于以i-1结尾的有效字符串的长度加2,即dp[i]=dp[i-1]+2;
比如:(()()),dp=[0 0 2 0 4 6]
但是:如果字符串是“()(()())”时,再按上面的式子算就会出错,我们需要再在pre的基础上再往前跳一步,再加上以pre-1结尾的有效字符串的长度
有一个问题:为什么只在pre的基础上跳了一步,而不是两步三步,因为跳了一步后,最后记下的字符串有效长度可以看作一个串,后面往前跳更多步,其实都是包含了这部分。
public class Problem_01_ParenthesesProblem {
public static boolean isValid(String str) {
if (str == null || str.equals("")) {
return false;
}
char[] chas = str.toCharArray();
int status = 0;
for (int i = 0; i < chas.length; i++) {
//非括号字符,如果输入满足要求的话,第一个if可以不要
if (chas[i] != ')' && chas[i] != '(') {
return false;
}
//当前右括号大于左括号,直接返回false
if (chas[i] == ')' && --status < 0) {
return false;
}
//统计遍历完后左括号的数量,如果status>0,说明左括号比右括号多
if (chas[i] == '(') {
status++;
}
}
return status == 0;
}
public static int maxLength(String str) {
if (str == null || str.equals("")) {
return 0;
}
char[] chas = str.toCharArray();
int[] dp = new int[chas.length];
int pre = 0;
int res = 0;
for (int i = 1; i < chas.length; i++) {
if (chas[i] == ')') {
pre = i - dp[i - 1] - 1;
if (pre >= 0 && chas[pre] == '(') {
dp[i] = dp[i - 1] + 2 + (pre > 0 ? dp[pre - 1] : 0);
}
}
res = Math.max(res, dp[i]);
}
return res;
}
public static void main(String[] args) {
String str1 = "((())())";
System.out.println(isValid(str1));
System.out.println(maxLength(str1));
String str2 = "(())(()(()))";
System.out.println(isValid(str2));
System.out.println(maxLength(str2));
String str3 = "()(()()(";
System.out.println(isValid(str3));
System.out.println(maxLength(str3));
}
}