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 result = 0;
int begin = -1; //记录合法子串的开始位置
stack<int> stk; //使用栈判断子串的合法性
for(int i=0;i<s.length();i++){
//左括号入栈
if(s[i]=='(') stk.push(i);
//扫描到右括号时,发现栈空,则将合法子串开始位置设置为当前位置
else if(stk.empty()) begin = i;
else{
//扫描到右括号时,栈不空,则左括号出栈,并更新合法子串长度
stk.pop();
if(stk.empty()) result = max(result,i-begin);
//左括号出栈后,栈不空的情况下,也需要更新一次子串长度
else result = max(result,i-stk.top());
}
}
return result;
}
};