问题:
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】若s[i]=='(' ,则压栈 stack.push(i);
【2】若s[i]=')' ,如果这个时候栈是空的,那么记录最后一个')'的位置: last=i ;
【3】如果s[i]=')' ,如果这个时候栈是非空的,弹栈:
(3.1)出栈后,如果栈为空,那么当前序列的最长合法括号的长度为i-last (匹配已经完成);
(3.2)出栈后,如果栈为非空,那么当前序列的最长合法括号的长度为i-buffer.top(). (匹配可能还没有完成);
代码:
class Solution{
public:
int longestValidParentheses(string s) {
int max_len=0;
//字符串中出现')',但存(的栈为空,那么last就存这个)的坐标
int last=-1;
//放'('的栈 stk
stack<int> stk;
for(int i=0;i<s.length();i++){
//只要遇到(就存栈stk
if(s[i]=='('){
stk.push(i);
//遇到)
}else{
//存(的栈空,有效的括号长度从last以后算起
if(stk.empty()){
last=i;
//(栈不空
}else{
stk.pop();
//刚好匹配,则长度为i-last;
//如果有多个()()(),i增而last不变,则长度是增加的
if(stk.empty()){
max_len=max(max_len,i-last);
}else{
//不匹配:((((),最大长度为i-stk.top()
max_len=max(max_len,i-stk.top());
}
}
}
}
return max_len;
}
};