問題:
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;
}
};