Longest Valid Parentheses

来源:互联网 发布:sql 查询一天内的数据 编辑:程序博客网 时间:2024/06/06 00:59

Longest Valid Parentheses

 Total Accepted: 1328 Total Submissions: 7382

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.

Go to Original!

一见到括号匹配,首先想到的就是栈了。

思路:维护两个栈,一个用来记录索引,另一个记录是左右括号;

一旦当前处理括号“)”和栈顶“(”相匹配构成一对,即扔掉。

最终如果栈为空时,字符长即为括号长。如果不为空,栈里元素肯定为无法匹配的括号。

核心,记录连续扔掉的匹配对的长度即为返回值。

int longestValidParentheses(string s) {  
    int max=0; 
    int l = s.length();

    stack<int> indexs;
    stack<bool> lefts;


    for(int i = 0; i < l; i++){
        if(s[i] == '('){
            indexs.push(i);
            lefts.push(true);
        }
        else{
            if(indexs.size() > 0 && lefts.top()){
                indexs.pop();
                lefts.pop();
                
                int tmp = indexs.empty() ? i + 1 : i - indexs.top();
                if(max < tmp) max = tmp;
            }
            else{
                indexs.push(i);
                lefts.push(false);
            }
        }
    }
    return max;  
}  

原创粉丝点击