关闭

Longest Valid Parentheses

标签: 动态规划
172人阅读 评论(0) 收藏 举报
分类:

题目描述

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
For “(()”, the longest valid parentheses substring is “()”, which has length = 2.
Another example is “)()())”, where the longest valid parentheses substring is “()()”, which has length = 4.

题目解答

解题思想

  • 遍历两遍, 第一遍把优先的’(’ 和 ‘)’ 转换成 ’ * ’ , 然后计算最长连续的*个数
  • 动态规划的思想

代码实现

public class Solution {
    public int longestValidParentheses(String s) {
       if(s == null || s.length() == 0)
            return 0;
        StringBuilder temp = new StringBuilder(s);
        ArrayDeque<Integer> stack = new ArrayDeque<>();
        for(int i = 0; i < s.length(); i++){
            if(s.charAt(i) == '(')
                stack.push(i);
            else if(!stack.isEmpty()){
                //注意
                temp.setCharAt(stack.pop(), '*');
                temp.setCharAt(i, '*');
            }
        }

        int longest = 0, part = 0;
        for(int i = 0; i < temp.length(); i++){
            if(temp.charAt(i) == '*'){
                part++;
            }else {
                longest = Math.max(longest, part);
                part = 0;
            }
        }

        //注意
        longest = Math.max(longest, part);
        return longest;
    }
}

DP

public class Solution {
    /**
     *
     1. 状态:
     DP[i]:以s[i-1]为结尾的longest valid parentheses substring的长度。

     2. 通项公式:
     s[i-1] = '(':
     DP[i] = 0

     s[i-1] = ')':找i前一个字符的最长括号串DP[i]的前一个字符j = i-2-DP[i-1]
     DP[i] = DP[i-1] + 2 + DP[j],如果j >=0,且s[j] = '('
     DP[i] = 0,如果j<0,或s[j] = ')'
     */
    public int longestValidParentheses(String s) {
       if(s == null || s.length() == 0 || s.length() == 1)
            return 0;


        int len = s.length();
        int[] dp = new int[len+1];
        Arrays.fill(dp, 0);

        int maxLen = 0;
        for(int i = 1; i < dp.length; i++){
            int j = i-2-dp[i-1];
            if(s.charAt(i-1) == '(' || j < 0 || s.charAt(j) == ')')
                dp[i] = 0;
            else {
                dp[i] = dp[i-1]+2+dp[j];
                maxLen = Math.max(dp[i], maxLen);
            }
        }

        return maxLen;
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:41924次
    • 积分:1858
    • 等级:
    • 排名:千里之外
    • 原创:148篇
    • 转载:1篇
    • 译文:0篇
    • 评论:1条
    博客专栏
    最新评论