description:
Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.
找符合规则的最长的括号Note:Example:
Example 1:Input: "(()"Output: 2Explanation: The longest valid parentheses substring is "()"Example 2:Input: ")()())"Output: 4Explanation: The longest valid parentheses substring is "()()"
answer:
class Solution {public: int longestValidParentheses(string s) { int res = 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(); res = m.empty() ? max(res, i - start + 1) : max(res, i - m.top()); //取出去之后同样有两种情况讨论 } } } return res; }};