您的位置:首页 > 其它

括号字符串的有效性和最长有效长度

2017-11-01 10:54 351 查看
/**
* Created by lxw, liwei4939@126.com on 2017/11/1.
* 括号字符串的有效性和最长有效长度
*/
public class bracketsIsValid {

public 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(chas[i] != '(' && chas[i] != ')'){
return false;
}
if(chas[i] == ')' && --status < 0){
return false;
}
if(chas[i] == '('){
status++;
}
}
return status == 0;
}

public 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){
bracketsIsValid tmp = new bracketsIsValid();
String str1 = "(())";
System.out.println(tmp.isValid(str1));

String str2 = "()(";
System.out.println(tmp.isValid(str2));

System.out.println(tmp.maxLength(str1));
System.out.println(tmp.maxLength(str2));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: