32. Longest Valid Parentheses

problem:

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.

Subscribe to see which companies asked this question

思路:

首先使用装左括号的栈,存放对应左括号的位置,stack<int> sta,遇到右括号则将栈顶元素弹出。

按顺序读取string中的字符,如果是左括号,则将挡枪位置入栈;

设置一个指针ptr标记匹配字符串的潜在起始位置。

如果是右括号,则有两种情况,一种是栈内为空,说明该右括号没有括号与之匹配,说明潜在ptr的位置需要更改,新的潜在位置至少为为右括号后面;另一种是栈内不为空,则计算相匹配字符串的长度。首先将当前栈顶元素弹出,若弹出后栈不为空,说明栈顶元素之后的位置都有相匹配的,即可计算长度;若栈为空,说明从潜在位置开始之后的全部匹配,也可计算相应的长度。

(其实ptr只是一个记录栈顶元素位置的量)

class Solution {
public:
    int longestValidParentheses(string s) {
        int result = 0;
        int length = s.length();
        stack<int> sta;
        int i;
        int local_first_left = 0; //用于记录第一个左括号的可能位置
        for(i=0; i<length; i++)
        {
            //若为左括号,则将左括号位置压栈
            if(s[i] == '(')
                sta.push(i);
            //若为右括号
            else
            {
                //若栈本身为空,则在右括号之前无左括号,修改第一个左括号的可能位置
                if(sta.empty())
                    local_first_left = i+1;
                //若栈不为空,则可计算字符串长度
                else
                {
                    sta.pop();
                    if(sta.empty())
                        result = max(result, i-local_first_left+1);
                    else
                        result = max(result, i-sta.top());
                }
            }
        }
        return result;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值