classSolution { public: intlongestValidParentheses(string s){ int n = s.size(); int 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(); // cout << s.size() << " " << s.length() << endl; int ans = 0; int left = 0, right = 0; for (int i = 0; i < n; i++){ if (s[i] == '('){ left += 1; }else{ right += 1; } if (left < right) { left = 0; right = 0; } if (left == right){ ans = max(ans, right*2); } }
left = right = 0; for (int i = n-1; i>0; i--){ if (s[i] == '('){ left += 1; }else{ right += 1; } if (left > right) { left = 0; right = 0; } if (left == right){ ans = max(ans, right*2); } } return ans; } };