LeetCode OJ 之 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.

给一个字符串只包含字符'(' 和 ')'。找出最长的有效括号的子串。

思路:

1、用栈实现,当前字符如果为'(',则把它的位置记录下来入栈,当前字符如果为')',则判断栈是否为空,如果为空,则说明当前字符')'失配,即没有字符能与它配对。则记录下失配的位置。如果栈非空,则可以计算当前串的最大匹配长度。

代码:

class Solution {
public:
    int longestValidParentheses(string s) 
    {
        stack<int> stk;
        int len = s.size();
        int miss = -1;//存储开始不匹配的位置,比如'(()))((()))',开始不匹配的位置是4,4之前的最大匹配长度是4,之后的最大匹配长度是6 
        int maxLen = 0;
        if(len <= 1)
            return 0;
        for(int i = 0 ; i < len ; i++)
        {
            if(s[i] == '(')
                stk.push(i);
            else
            {
                if(stk.empty())
                    miss = i;
                else
                {
                    //每找到一个括号对,把匹配的'('的位置出栈
                    stk.pop();
                    //如果栈为空,则减去失配的位置即是匹配的最大括号长度
                    if(stk.empty())
                        maxLen = max(maxLen , i - miss);
                        
                    //如果栈非空,则与当前')'匹配的括号的位置为栈顶
                    else
                        maxLen = max(maxLen , i - stk.top());
                }
            }
        }
        return maxLen;
    }
};




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值