首页 > 其他 > 详细

[LeetCode]32.Longest Valid Parentheses

时间:2015-04-23 21:48:31      阅读:261      评论:0      收藏:0      [点我收藏+]

题目

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;
}

运行时间

技术分享

[LeetCode]32.Longest Valid Parentheses

原文:http://blog.csdn.net/sunnyyoona/article/details/45226477

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!