首页 > 代码库 > 【LeetCode】Longest Valid Parentheses

【LeetCode】Longest Valid Parentheses

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.

 

括号匹配的常规思路就是用进出栈。

但是这题的关键在于“连续匹配”,因此计算“连续匹配”长度时,本质就是求不匹配的括号之间最大长度。

也就是求进栈但未出栈的括号下标之间的最大差值,注意边界值:第一个留在栈中的括号之前的连续匹配长度。

 

class Solution {public:    int longestValidParentheses(string s) {        int ret = 0;        stack<int> stk;   //store the indexes of unmatched parentheses        for(int i = 0; i < s.size(); i ++)        {            if(s[i] == ()            //unmatch                stk.push(i);            else            {//s[i] == ‘)‘                if(!stk.empty() && s[stk.top()] == ()                //match                    stk.pop();                else                //unmatch                    stk.push(i);            }        }        if(stk.empty())        //all match            ret = s.size();        else        {//check every unmatched pair of parentheses            int start;            int end = s.size()-1;            while(!stk.empty())            {                start = stk.top();                stk.pop();                ret = max(ret, end-start);                end = start-1;            }            //from begin to the first unmatched parenthese            ret = max(ret, end+1);        }        return ret;    }};

【LeetCode】Longest Valid Parentheses