dp版本
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.length();
vector<int> f(n, 0);
//f[i]以i结尾的最长子串 只考虑s[i]==')'
//s[i]==')'
//1:s[i-1]=='(' f[i]=f[i-1]+2;
//2:s[i-1]==')'&&s[i-f[i-1]-1]=='(' f[i]=f[i-1]+2 +f[i-f[i-1]-1-1]
for (int i = 1; i < n; i++)
if (s[i] == ')') {
if (s[i - 1] == '(') {
f[i] = (i>=2? f[i - 2]:0) + 2;
}
else {
if (i - f[i - 1] - 1 >= 0 && s[i - f[i - 1] - 1] == '(')
f[i] = f[i - 1] + 2 + ((i - f[i - 1] - 2>=0)?f[i - f[i - 1] - 2]:0);
}
}
int ans = 0;
for (int i = 0; i < n; i++) if(s[i]==')')ans = max(ans, f[i]);
return ans;
}
};
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> stk;
int res=0;
int start=-1;
for(int i=0;i<s.size();i++){
if(s[i]=='('){
stk.push(i);
}
else{
if(stk.size()){
stk.pop();
if(stk.size()) res=max(res,i - (stk.top() + 1) + 1);
else res=max(res,i-start);
}
else{
start=i;
}
}
}
return res;
}
};