题目链接:https://leetcode-cn.com/problems/longest-valid-parentheses/
给定一个只包含 '(' 和 ')' 的字符串,找出最长的包含有效括号的子串的长度。
示例 1:输入: "(()"
输出: 2
解释: 最长有效括号子串为 "()"
示例 2:
输入: ")()())"
输出: 4
解释: 最长有效括号子串为 "()()"
因为这道题需要统计最长有效括号子串的长度,所以拿下标来做最好。也就是在栈里存储下标。
因为,只有两种字符,分两种情况:
注意:
class Solution {
public:
int longestValidParentheses(string s) {
int max_count = 0, count =0;
stack brackets;
// 初始化栈 -1
brackets.push(-1);
for (int i = 0;i < s.size();i++) {
// 如果字符为‘(’ 那么就把下标放进栈中
if (s[i] == '(') {
brackets.push(i);
}
// 字符为‘)’
else {
// 不论怎样 先pop
brackets.pop();
// 如果栈空了 记录当前字符的下标到栈底
if (brackets.empty()) {
brackets.push(i);
}
// 计算子串的长度
count = i-brackets.top();
max_count = max_count > count ? max_count : count;
}
}
return max_count;
}
};