zoukankan      html  css  js  c++  java
  • 32. Longest Valid Parentheses (JAVA)

    Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

    Example 1:

    Input: "(()"
    Output: 2
    Explanation: The longest valid parentheses substring is "()"
    

    Example 2:

    Input: ")()())"
    Output: 4
    Explanation: The longest valid parentheses substring is "()()"
    class Solution {
        public int longestValidParentheses(String s) {
            int[] dp = new int[s.length()]; //longest valid parentheses end with current index
            Stack<Integer> stack = new Stack<>(); //index of each left parenthese
            int ret = 0;
            
            for(int i = 0; i < s.length(); i++){
                if(s.charAt(i) == '('){
                    stack.push(i);
                }
                else if(!stack.empty()){ //')' and have left parenthese in the stack
                    if(stack.peek() > 0)
                        dp[i] = dp[stack.peek()-1] + (i-stack.peek()+1);
                    else //first index
                        dp[i] = i-stack.peek()+1;
                    stack.pop();
                }
                else{ //')' and have no left parenthese in the stack
                    stack.clear();
                }
            }
            
            for(int i = 0; i < s.length(); i++){
                if(dp[i]>ret) ret = dp[i];
            }
            return ret;
        }
    }

    最长有效括号不仅与当前stack的情况有关,也与有效做括号之前的stack情况有关,所以用动态规划。

    使用一维动态规划记录以当前位置结束的最长有效括号。

  • 相关阅读:
    python之编写购物车(第二天)
    day6作业--游戏人生
    day7 socket网络编程基础
    day7 --socket网络编程基础
    Python类和人类
    day7 socket网络编程
    day7异常处理
    day7面向对象--反射
    day6面向对象--类的特殊成员方法
    使用BigDecimal来进行精确计算
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/10811804.html
Copyright © 2011-2022 走看看