class Solution { public: /** * * @param s string字符串 * @return int整型 */ int longestValidParentheses(string s) { int count = 0, bal = 0; int res = 0; for (auto &c : s) { if (c == '(') { ++count; ++bal; } else { --bal; } if (bal == 0) { res = max(res, count * 2); } if (bal < 0) { count = 0; bal = 0; } } count = 0, bal = 0; for (auto it = s.rbegin(); it != s.rend(); ++it) { auto c = *it; if (c == ')') { ++count; ++bal; } else { --bal; } if (bal == 0) { res = max(res, count * 2); } if (bal < 0) { count = 0; bal = 0; } } return res; } };
思路:正反两次遍历+贪心。