【LeetCode】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.

【解析】

题意:给定一个包含左右括号的字符串,找出其中最长的有效子串,返回其长度。

思路:动态规划。用一个数组len[i]记录以i结尾的最长有效子串长度,如")()())"的动规数组为[0, 0, 2, 0, 4, 0]。具体做法是,从前往后遍历数组,遇到左括号,len[i]=0,遇到右括号,就往前找第一个多余的左括号的位置。首先跳过i前面的有效连续子串,碰到第一个没有匹配的括号p,如果p是右括号,那么p和i无法匹配,len[p]=0;如果p是左括号,那么p刚好和i匹配,此时要p到i都是有效子串,同时还要加上p前面连续的有效子串。

【Java代码】

public class Solution {
    public int longestValidParentheses(String s) {
        int longest = 0;
        
        int[] len = new int[s.length()];
        for (int i = 1; i < s.length(); i++) {
            if (s.charAt(i) == '(') {
                len[i] = 0;
            } else {
                // find the nearest parentheses before i that not matched
                int p = i - 1;
                while (p >= 0 && len[p] > 0) {
                    p -= len[p];
                }
                
                // if p is left parentheses, then it mathches i
                if (p >= 0 && s.charAt(p) == '(') {
                    len[i] = i - p + 1;
                    
                    // add the length that matched before p 
                    if (p > 0) {
                        len[i] += len[p - 1];
                    }
                    
                    // update the parentheses length
                    longest = Math.max(longest, len[i]);
                }
            }
        }
        
        return longest;
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值