版权声明:本文为博主原创文章,未经博主允许不得转载。如有错误,欢迎指出~(@^_^@)~ https://blog.csdn.net/zwj1452267376/article/details/62334938
这里有另一个关于处理合法的括号序列的问题。
如果插入“+”和“1”到一个括号序列,我们能得到一个正确的数学表达式,我们就认为这个括号序列是合法的。例如,序列"(())()", "()"和"(()(()))"是合法的,但是")(", "(()"和"(()))("是不合法的。
这里有一个只包含“(”和“)”的字符串,你需要去找到最长的合法括号子段,同时你要找到拥有最长长度的子段串的个数。
Input
第一行是一个只包含“(”和“)”的非空的字符串。它的长度不超过 1000000。
Output
输出合格的括号序列的最长子串的长度和最长子串的个数。如果没有这样的子串,只需要输出一行“0 1”。
Input示例
)((())))(()())
Output示例
6 2
题解:看错题目了,以为是找所有合法子串个数。想了半天,发现是找最长的。 那么就很简单了,用一个栈维护,将没办法形成匹配的括号及其位置放进一个栈里面,那么最后栈内每两个括号之间就有一个合法串,然后从前往后扫一遍,记录下最长合法串长度及其个数就好了。
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace std;
const int maxn = 1e6+10;
struct node
{
int id;
char s;
}temp;
stack<node> tac;
char str[maxn];
int main()
{
while(scanf("%s",str)!=EOF)
{
int len=strlen(str);
int Max=0,cnt=1;
while(!tac.empty())
tac.pop();
for(int i=0;i<len;++i)
{
if(str[i]=='(')
{
temp.id=i;
temp.s='(';
tac.push(temp);
}
else
{
if(tac.empty())
{
temp.id=i;
temp.s=')';
tac.push(temp);
}
else
{
temp=tac.top();
if(temp.s==')')
{
temp.id=i;
tac.push(temp);
}
else
tac.pop();
}
}
}
if(tac.empty())
Max=len;
else
{
temp=tac.top();
int L=len-temp.id-1;
Max=L;
while(!tac.empty())
{
temp=tac.top();
tac.pop();
if(tac.empty()){
if(temp.id>Max)
{
Max=temp.id;
cnt=1;
}
else if(temp.id==Max)
cnt++;
}
else
{
node step=tac.top();
L=temp.id-step.id-1;
if(L==Max)
cnt++;
else if(L>Max){
cnt=1;
Max=L;
}
}
}
}
if(Max==0)
cnt=1;
printf("%d %d\n",Max,cnt);
}
return 0;
}