题目:
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.
思路:
1、用栈实现,当前字符如果为'(',则把它的位置记录下来入栈,当前字符如果为')',则判断栈是否为空,如果为空,则说明当前字符')'失配,即没有字符能与它配对。则记录下失配的位置。如果栈非空,则可以计算当前串的最大匹配长度。
代码:
class Solution {
public:
int longestValidParentheses(string s)
{
stack<int> stk;
int len = s.size();
int miss = -1;//存储开始不匹配的位置,比如'(()))((()))',开始不匹配的位置是4,4之前的最大匹配长度是4,之后的最大匹配长度是6
int maxLen = 0;
if(len <= 1)
return 0;
for(int i = 0 ; i < len ; i++)
{
if(s[i] == '(')
stk.push(i);
else
{
if(stk.empty())
miss = i;
else
{
//每找到一个括号对,把匹配的'('的位置出栈
stk.pop();
//如果栈为空,则减去失配的位置即是匹配的最大括号长度
if(stk.empty())
maxLen = max(maxLen , i - miss);
//如果栈非空,则与当前')'匹配的括号的位置为栈顶
else
maxLen = max(maxLen , i - stk.top());
}
}
}
return maxLen;
}
};