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.
stack是解这种valid pari的不二法宝。。。
1. 维护一个stack, 只存 ‘(’ 的index
2. 同时维护一个start,记录最开始有效的位子。
3. 每遇到‘)’,如果stk不为空 pop 并求最长 (根据是否为空) , 如果为空,那么不是valid, 更新 start.
O(n)
class Solution {
public:
int longestValidParentheses(string s) {
int len=s.size();
int maxLen=0, start=0;
stack<int> stk;
for (int i=0; i<len; i++){
if (s[i]=='(')
stk.push(i);
else{
if (stk.empty()){
start=i+1;
} else{
stk.pop();
maxLen=max(maxLen, stk.empty()? i-start+1: i-stk.top());
}
}
}
return maxLen;
}
};