classSolution { public: intlongestValidParentheses(string s){ int n = s.size(), ans = 0; stack<int> stk; stk.push(-1); for (int i = 0; i < n; ++i) { if (s[i] == '(') stk.push(i); else { stk.pop(); if (stk.empty()) stk.push(i); else ans = max(ans, i - stk.top()); } } return ans; } };
classSolution { public: intlongestValidParentheses(string s){ int n = s.size(), ans = 0; int l = 0, r = 0; for (int i = 0; i < n; ++i) { if (s[i] == '(') ++l; else ++r; if (l == r) ans = max(ans, 2 * r); elseif (r > l) l = r = 0; } l = r = 0; for (int i = n-1; ~i; --i) { if (s[i] == '(') ++l; else ++r; if (l == r) ans = max(ans, 2 * l); elseif (l > r) l = r = 0; } return ans; } };