题目描述
给定一个字符串str,返回其最长有效括号子串的长度。
- 有效的括号字符串是指只包含小括号,不包含其他字符,且满足括号语法规则的字符串,例如“(())”是有效的,“((a))”、“(()”、“{()}”是无效的。
- 有效括号子串是指输入字符串中满足有效括号字符串规则的子串,例如“()(()()(”的有效括号子串包括“()”和“()()”,其最长的有效括号字串长度即为4。
分析
以“()(()()(”来分析:
我们先讨论匹配的情况,匹配的话对匹配个数加1。然后将括号去除,那么我们可以用栈来实现。
从左往右计算的话会出现这样的问题“(()((”,相同的字符’(‘,我们无法判断停止条件:
因而将从左往右计算改为从右往左计算:遇到’)’即入栈,有与之相配的’(‘将其出栈,匹配个数加1,要么遇到其他字符时全部出栈,匹配个数上限;若遇到’(‘字符并且栈为空时,匹配个数上限。
总代码
#include<iostream>
#include<string>
#include<vector>
#include<stack>
using namespace std;
int calc(const string& str,int& tail) {
stack<char> s;
int max = 0;
int count = 0;
while (tail >= 0) {
if (str[tail] == '(' && s.size() == 0 || (str[tail]!=')' && str[tail]!='(')) {
while (s.size() != 0) {
s.pop();
}
if (max < count)
max = count;
count = 0;
}
else if (str[tail] == '(' && s.top() == ')') {
s.pop();
++count;
}
else if (str[tail] == ')') {
s.push(str[tail]);
}
--tail;
}
if (max < count) {
max = count;
}
return max*2;
}
int main(int argc, char* argv[]) {
string str;
cin >> str;
int len = str.length();
if (len < 2)
cout << 0 << endl;
--len;
cout << calc(str,len) << endl;
getchar();
return 0;
}