32. Longest Valid Parentheses
Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())
" Output: 4 Explanation: The longest valid parentheses substring is"()()"
AC code:
class Solution { public: int longestValidParentheses(string s) { int n = s.length(), longest = 0; stack<int> st; for (int i = 0; i < n; i++) { if (s[i] == '(') st.push(i); else { if (!st.empty()) { if (s[st.top()] == '(') st.pop(); else st.push(i); } else st.push(i); } } if (st.empty()) longest = n; else { int a = n, b = 0; while (!st.empty()) { b = st.top(); st.pop(); longest = max(longest, a-b-1); a = b; } longest = max(longest, a); } return longest; } };
Runtime: 8 ms, faster than 62.98% of C++ online submissions for Longest Valid Parentheses.
永远渴望,大智若愚(stay hungry, stay foolish)