题目
给一个只包含'('
和')'
的字符串,找出最长的有效(正确关闭)括号子串的长度。
对于 "(()"
,最长有效括号子串为 "()"
,它的长度是 2
。
另一个例子 ")()())"
,最长有效括号子串为 "()()"
,它的长度是4
。
方法一
这道题可以考虑用栈来实现,这样一次遍历就可以OK了。假定(
用数字-2
表示,)
用数字-1
表示,正数表示现阶段可以组成封闭括号的长度。
如果遇到(
直接入栈
如果遇到)
考虑如下几种情况:
1、栈为空,此时直接continue
即可
2、栈顶为(
,则可以配对,栈弹出栈顶元素,如果此时栈顶为正数,则弹出正数加2
重新入栈,否则直接压入2
3、栈顶为正数,则弹出栈顶元并记录,此时针对栈顶元考虑步骤1
和2
的情况。
代码如下
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
int res=0;
for(int i=0;i<s.size();i++){
if(s[i]=='('){
st.push(-2);
continue;
}
if(st.empty()) continue;
if(st.top()==-2){
st.pop();
if(st.empty()||st.top()<0) st.push(2);
else{
int tmp=st.top()+2;
st.pop();
st.push(tmp);
}
res=max(res,st.top());
continue;
}
if(st.top()>0){
int tmp=st.top();
st.pop();
if(st.empty()) continue;
else{
tmp+=2;
st.pop();
while(!st.empty()&&st.top()>0){
tmp+=st.top();
st.pop();
}
st.push(tmp);
res=max(res,st.top());
}
}
}
return res;
}
};
方法二
这题可以用动态规划求解,开一个数组vector<int> count
表示以i
位置结尾的最长有效括号子串的长度。如果s[i]==')'
且j=i-1-count[i-1];
s[i-1]=='('
,则j=i-1
,此时考虑count[i]=2+count[i-2]=2+count[j-1]
s[i-1]==')'
,则j=i-1-count[i-1]
,此时如果s[j]=='('
,则count[i]=2+count[i-1]+count[j-1]
(例如s=()(())
)- 综合上述两种情况,可以写成
count[i]=2+count[i-1]+count[j-1]
代码
class Solution {
public:
int longestValidParentheses(string s) {
int n=s.size(),res=0;
vector<int> count(n,0);
for(int i=1;i<n;i++){
if(s[i]=='(') continue;
int j=i-1-count[i-1];
if(s[j]=='(')
count[i]=2+count[i-1]+(j>0?count[j-1]:0);
res=max(res,count[i]);
}
return res;
}
};