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


dp+栈。用一个dp数组来存储结果,dp[i]表示以第i个位置的括号结尾所能得到的最长合法子串长度,则所有的左括号位置对应的dp值都是0。以)(()()))为例,其dp的值依次为0,0,0,2,0,4,6,0。那么我们得到这个dp数组的值后只要从前到后扫一遍取出最大的值就可以了。

而这个dp数组,我们需要借助一个栈来计算:

从前到后遍历原始的字符串,如果在第i个位置碰到一个'(',令dp[i]=0,并把i压入栈中;

如果在第i个位置碰到一个')',这时我们需要先看下栈是否为空。如果栈为空则表示当前没有'('可与这个')'配对,则dp[i]=0;如果栈不为空,弹出栈顶元素pos,它记录的是与这个')'配对的'('的位置,易知pos和i之间的序列一定都是合法的,那么dp[i]=dp[pos-1]+(i-pos+1);


int longestValidParentheses(string s) {
    int n = s.length();
    int *dp = new int [n+1];
    memset(dp,0,sizeof(int)*(n+1));
    stack<int> st;
    for(int i=1;i<=n;i++){
        if(s[i-1]=='('){
            dp[i]=0;
            st.push(i);
        }
        else{
            if(st.empty()){
                dp[i]=0;
            }
            else{
                int pos=st.top();
                st.pop();
                dp[i]=dp[pos-1]+(i-pos+1);
            }
        }
    }
    int max_len=0;
    for(int i=1;i<=n;i++){
        if(dp[i]>max_len)max_len=dp[i];
    }
    return max_len;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值