[LeetCode]32.Longest Valid Parentheses

160 篇文章 28 订阅

题目

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.

思路

栈中保存的不是字符(而是字符(所在的下标。
如果遇到字符(,无条件压入栈中;
如果遇到字符),并且栈为空,说明这是一个无法匹配的字符),用变量last记录下标。last存放的其实是最后一个无法匹配的字符)。
如果遇到字符),并且栈不为空,我们可以消除一对括号(栈顶元素出栈)。

  • 如果栈为空,用当前元素下标i 减去 last计算有效长度;
  • 如果栈不为空,用当前元素下标i 减去 栈顶元素下标计算有效长度;

代码

/*---------------------------------------------------------
*   日期:2015-04-23
*   作者:SJF0115
*   题目: 32.Longest Valid Parentheses
*   网址:https://leetcode.com/problems/longest-valid-parentheses/
*   结果:AC
*   来源:LeetCode
*   博客:
------------------------------------------------------------*/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;

class Solution {
public:
    int longestValidParentheses(string s) {
        int size = s.size();
        if(size <= 1){
            return 0;
        }//if
        int last = -1;
        int Max = 0;
        stack<int> leftStack;
        for(int i = 0;i < size;++i){
            // (入栈
            if(s[i] == '('){
                leftStack.push(i);
            }//if
            else if(s[i] == ')'){
                if(leftStack.empty()){
                    last = i;
                }//if
                else{
                    leftStack.pop();
                    if(leftStack.empty()){
                        Max = max(Max,i - last);
                    }//if
                    else{
                        Max = max(Max,i - leftStack.top());
                    }//else
                }//else
            }//else
        }//for
        return Max;
    }
};

int main(){
    Solution solution;
    string str("()(()");
    cout<<solution.longestValidParentheses(str)<<endl;
    return 0;
}

运行时间

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@SmartSi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值