problem:
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.
Subscribe to see which companies asked this question
首先使用装左括号的栈,存放对应左括号的位置,stack<int> sta,遇到右括号则将栈顶元素弹出。
按顺序读取string中的字符,如果是左括号,则将挡枪位置入栈;
设置一个指针ptr标记匹配字符串的潜在起始位置。
如果是右括号,则有两种情况,一种是栈内为空,说明该右括号没有括号与之匹配,说明潜在ptr的位置需要更改,新的潜在位置至少为为右括号后面;另一种是栈内不为空,则计算相匹配字符串的长度。首先将当前栈顶元素弹出,若弹出后栈不为空,说明栈顶元素之后的位置都有相匹配的,即可计算长度;若栈为空,说明从潜在位置开始之后的全部匹配,也可计算相应的长度。
(其实ptr只是一个记录栈顶元素位置的量)
class Solution {
public:
int longestValidParentheses(string s) {
int result = 0;
int length = s.length();
stack<int> sta;
int i;
int local_first_left = 0; //用于记录第一个左括号的可能位置
for(i=0; i<length; i++)
{
//若为左括号,则将左括号位置压栈
if(s[i] == '(')
sta.push(i);
//若为右括号
else
{
//若栈本身为空,则在右括号之前无左括号,修改第一个左括号的可能位置
if(sta.empty())
local_first_left = i+1;
//若栈不为空,则可计算字符串长度
else
{
sta.pop();
if(sta.empty())
result = max(result, i-local_first_left+1);
else
result = max(result, i-sta.top());
}
}
}
return result;
}
};