28 - 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.


solution: 关键在于建立栈来保存左括号信息。

一开始只存做括号,发现这样做行不通,没有考虑(()这种情况,即左括号多余,这种情况包括()(()和()(())两种,因此考虑到需要存左括号的索引值,这样建立一个int栈来保存左括号的索引,并且保存非法括号的结束值start,初值应该是-1(不能是0,考虑到初始化的状况,即假定0之前是非法,所以是-1);从头依次向尾扫,如果遇到左括号则压栈;遇到右括号则考虑栈是否空,空的话那么之前的括号序列非法,所以start的值设置在该点;若栈不为空,则弹出一个左括号和该右括号匹配,然后计算长度(当弹栈后,若栈不为空,那么可知左括号多余了,所以要计算的是从最后一个不匹配的左括号到该点的长度;若此时栈空,那么就计算从start到该点的长度),最后和全局变量longestVP比对,保留最大值。


class Solution {
public:
    int longestValidParentheses(string s) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if(s == "" || s.size() <= 1)
            return 0;
            
        int len = s.size();
        int longestVP = 0;
        int start = -1;
        
        vector<int>leftp;
        
        int index = 0;
        while(index < len)
        {
            char temp = s.at( index );
            if(temp == '(')
            {
                leftp.push_back(index);
            }
            else
            {
                if( leftp.empty() )
                {
                    start = index;
                }
                else
                {
                    leftp.pop_back();
                    
                    if( leftp.empty() )
                    {
                        longestVP = max(longestVP, index - start);
                    }
                    else
                    {
                        longestVP = max(longestVP, index - leftp.back());
                    }
                    
                }
            }
                
            index++;
        }
        
        
        return longestVP;
    }
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值