版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
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 "()()"
考察:最大有效括号匹配长度,用栈保存括号的index,如果是'('则压栈,否则,要判断栈是否非空才可以弹出。
class Solution {
public:
int longestValidParentheses(string s) {
int res = 0, start = 0;
stack<int> ss;
for (int i = 0; i < s.length(); i ++) {
if (s[i] == '(')
ss.push(i);
else {
if (ss.empty())
start = i+1;
else {
ss.pop();
res = ss.empty() ? max(i-start+1, res) : max(res, i-ss.top());//已经pop了,则不需要+1
}
}
}
return res;
}
};
完,