Given a string containing just the characters '('
and ')'
, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"Output: 2Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"Output: 4Explanation: The longest valid parentheses substring is "()()"
代码:
class Solution {public: int longestValidParentheses(string s) { int ans = 0, start = 0; stack 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; }};
最长有效括号