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

来源:互联网 发布:石家庄优化公司 编辑:程序博客网 时间:2024/05/29 13:57

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

440

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

#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;}


0 0
原创粉丝点击