LeetCode第32题:Longest Valid Parentheses最长有效括号(Java实现)

题目: 

解答: 

class Solution {
    public int longestValidParentheses(String s) {
        int max=0;
        for(int i=0;i<s.length();i++){
            for(int j=i+2;j<=s.length();j+=2){
               if(isValid(s.substring(i,j))&&(j-i)>max){
                   max=j-i;
               }
            }
        }
        return max;
    }
    //创建一个方法,判断该String是否完全满足符号正确性!如果只有部分正确,仍然返回错误false!
    public boolean isValid(String s){
        //实例化栈
        Stack<Character> stack=new Stack<Character>();
        for(int i=0;i<s.length();i++){
            //逐一判断s,如果s在i位置上的字符为‘(’,则加入栈
            if(s.charAt(i)=='('){
                stack.push('(');
            }else if(!stack.empty()&&stack.peek()=='('){//如果s在i位置上的字符为')',判断栈是否为空,如果不是空的话接着判断栈最顶层的数据是否为'(',如果是则删除栈的最顶层
                stack.pop();
            }else{
                return false;
            }
        }
        return stack.empty();//如果最后空了,说明s完全满足符号的正确性。
    }
}

算法超时!说明不行。

另外一种:采用动态规划的方法

public class Solution {
    public int longestValidParentheses(String s) {
        int maxans = 0;
        int dp[] = new int[s.length()];
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == ')') {
                if (s.charAt(i - 1) == '(') {
                    dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
                } else if (i - dp[i - 1] > 0 && s.charAt(i - dp[i - 1] - 1) == '(') {
                    dp[i] = dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2;
                }
                maxans = Math.max(maxans, dp[i]);
            }
        }
        return maxans;
    }
}

猜你喜欢

转载自blog.csdn.net/FaustoPatton/article/details/87903469