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

题目: 

LeetCode第32题:Longest Valid Parentheses最长有效括号(Java实现)_第1张图片

解答: 

class Solution {
    public int longestValidParentheses(String s) {
        int max=0;
        for(int i=0;imax){
                   max=j-i;
               }
            }
        }
        return max;
    }
    //创建一个方法,判断该String是否完全满足符号正确性!如果只有部分正确,仍然返回错误false!
    public boolean isValid(String s){
        //实例化栈
        Stack stack=new Stack();
        for(int i=0;i

算法超时!说明不行。

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

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;
    }
}

 

你可能感兴趣的:(LeetCode习题集,LeetCode习题集)