32. Longest Valid Parentheses
problem description
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"algorithm thought
code
//use two stack
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st1;
st1.push(0);
stack<char> st2;
int res=0;
for(auto ch:s){
if(ch=='('){
st1.push(0);
st2.push(ch);
}else{
if(st2.empty()){
st1.push(0);
}else{
st2.pop();
int tmp=st1.top();
st1.pop();
tmp+=2;
tmp+=st1.top();
st1.pop();
res=max(res,tmp);
st1.push(tmp);
}
}
}
return res;
}
};
//use one stack
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> st;
int startpos=-1;
int res=0;
for(int i=0;i<s.size();++i){
if(s[i]=='('){
st.push(i);
}else{
if(st.empty())
startpos=i;
else{
st.pop();
if(st.empty()){
res=max(res,i-startpos);
}else{
res=max(res,i-st.top());
}
}
}
}
return res;
}
};algorithm analysis
Last updated