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: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
answer:
class Solution {
public:
int longestValidParentheses(string s) {
int res = 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();
res = m.empty() ? max(res, i - start + 1) : max(res, i - m.top());
//取出去之后同样有两种情况讨论
}
}
}
return res;
}
};