您的位置:首页 > 其它

zzulioj--10465--最长匹配子串(栈模拟)

2016-04-13 21:39 357 查看


10456: 最长匹配子串

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 133  Solved: 27

[Submit][Status][Web
Board]


Description

定义一个满足括号匹配的字符串为完美串。一个由'(',')'组成的字符串,怎么才能求出

来字符串S中最长的完美串(S的子串)的长度呢?


Input

输入的第一行是一个数字k,代表输入的样例组数(k < 100)。

每组样例是一个字符串只由'(',')'这两个字符组成的字符串s(|s| < 100000)。


Output

输出s中最长的匹配子串的长度。


Sample Input

3
()()
((())
(


Sample Output

4
4
0

思路:因为是要找连续的括号配对,如果我们知道最长的括号配对序列的两个端点的坐标的话我们就可以找出最长的长度,这里我用两个栈模拟括号配对,括号进栈的同时我们记录他的坐标,括号出栈的时候对应的数字栈也一并出栈,这样的话最后栈里剩下的括号跟数字栈中的数字是对应的,这些括号是不能配对的,但是他们两侧的括号是可以完成配对的,模拟有点坑,需要加一些小技巧还有判断

#include<cstdio>
#include<cstring>
#include<cmath>
#include<stack>
#include<algorithm>
using namespace std;
char str[100000];
stack<char>q;
stack<int>p;
int main()
{
int t;
scanf("%d",&t);
getchar();
while(t--)
{
memset(str,0,sizeof(str));
while(!q.empty()) q.pop();
while(!p.empty()) p.pop();
scanf("%s",str);
int l=strlen(str);
p.push(1);
for(int i=0;i<l;i++)
{
if(q.empty())
{
q.push(str[i]);
p.push(i+1);
continue;
}
if(str[i]==')')
{
char ch=q.top();
if(ch=='(')
{
q.pop();
p.pop();
}
else if(ch==')'||q.empty())
{
q.push(str[i]);
p.push(i+1);
}
}
else
{
q.push(str[i]);
p.push(i+1);
}
}
p.push(l);
int pre,now;
if(q.empty()) printf("%d\n",l);
else
{
now=p.top();
p.pop();
int maxx=0;
while(!p.empty())
{
pre=p.top();
p.pop();
int s=now-pre;
if(s==1)
s=0;
maxx=max(maxx,s);
now=pre;
}
if(maxx&1) maxx-=1;
printf("%d\n",maxx);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: