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

来源:互联网 发布:淘宝卖家可以延长多久 编辑:程序博客网 时间:2024/06/05 10:38
/** * 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));    }}