Leetcode32:Longest Valid Parentheses

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.

第一种解法是dynamic programming的解法,dp的解法可以从后面往前面推,或者从前面往后面推, 这一题我借鉴了ziyi_Google的写法:
https://leetcodenotes.wordpress.com/2013/10/19/leetcode-longest-valid-parentheses-%E8%BF%99%E7%A7%8D%E6%8B%AC%E5%8F%B7%E7%BB%84%E5%90%88%EF%BC%8C%E6%9C%80%E9%95%BF%E7%9A%84valid%E6%8B%AC%E5%8F%B7%E7%BB%84%E5%90%88%E6%9C%89%E5%A4%9A/

先定义dp中的数组opt, opt[i]就是代表从字符串i开始的位置,往后面数,longest valid parentheses. 这样的话就会有这样的情况
s[i] = ‘)’ 那么 dp[i] = 0, 因为从第i个位置开始的时候。如果字符是右括号 ‘)’. 那么从第i个位置开始的时候,肯定不能组成一个valid的parentheses.
所以dp数组推导公式就是
if(s[i]==’)’) dp[i] = 0;
if(s[i]==’(‘) dp[i] = dp[i+1]+2;

int j = (i + 1) + d[i + 1];
if (j < s.length() && s.charAt(j) == ‘)’) {
d[i] = d[i + 1] + 2; //(()())的外包情况
if (j + 1 < s.length())
d[i] += d[j + 1];//()()的后面还有的情况
//这种情况dp[i] = dp[i] + dp[j+1]; 适合 (()()()) ()()

代码如下:

public int longestValidParentheses(String s) {
    if (s.length() == 0)
        return 0;
    int maxLen = 0;
    int[] d = new int[s.length()];
    // d[i] means substring starts with i has max valid lenth of d[i]
    d[s.length() - 1] = 0;
    for (int i = s.length() - 2; i >= 0; i--) {
        if (s.charAt(i) == ')')
            d[i] = 0;
        else {
            int j = (i + 1) + d[i + 1];
            if (j < s.length() && s.charAt(j) == ')') {
                d[i] = d[i + 1] + 2; //(()())的外包情况
                if (j + 1 < s.length())
                    d[i] += d[j + 1];//()()的后面还有的情况
            }
        }
        maxLen = Math.max(maxLen, d[i]);
    }
    return maxLen;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值