32. Longest Valid Parentheses
Posted ruruozhenhao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
以上是关于32. Longest Valid Parentheses的主要内容,如果未能解决你的问题,请参考以下文章