https://leetcode.com/problems/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"()()"
代码:
class Solution { public: int longestValidParentheses(string s) { int ans = 0, start = 0; stack<int> m; for (int i = 0; i < s.size(); ++i) { if (s[i] == '(') m.push(i); else if (s[i] == ')') { if (m.empty()) start = i + 1; else { m.pop(); if(m.empty()) ans = max(ans, i - start + 1); else ans = max(ans, i - m.top()); } } } return ans; } };
最长有效括号