Sample Input
([(][()]]() ([)]
Sample Output
[()]
题意 : 求括号序列的最长合法序列 , 没有合法的不用输出;
用栈实现匹配,匹配的标为1 ,同时记下在序列中的下标,用结构体存好了;
#include<cstdio> #include<cstring> #include<map> #include<vector> #include<cmath> #include<cstdlib> #include<stack> #include<queue> #include <iomanip> #include<iostream> #include<algorithm> using namespace std ; struct node { char c ; int num ; }e[101000]; char s[101000] ; int match[101000]; int top ; int main() { int t = 0 ; while(~scanf("%s",s)) { int len = strlen(s); for( int i = 0 ; i < len ; i++) { e[i].c=s[i] ; e[i].num=i; } memset(match,0,sizeof(match)) ; stack<node>a ; for(int i = 0 ; i < len ; i++) { if(!a.empty()) { int w=a.top().num ; char ch=a.top().c ; if( ch=='(' && e[i].c == ')' || ch=='[' && e[i].c == ']') { match[i]=1 ; match[w]=1; a.pop(); } else a.push(e[i]) ; } else a.push(e[i]) ; } int flag=0,wan=0 , cout=0, MAX=0; for(int i = 0 ; i< len ; i++) { if(match[i]==1) cout++; else { if(cout>MAX) { MAX=cout ; wan=i-1 ; } cout=0; } if(cout) flag=1; } if(!flag) puts(""); else { if(cout) //最后一个没有处理,最后一段1 { if(cout>MAX) { MAX=cout; wan=len-1; } } for(int i = wan-MAX+1 ; i <= wan ;i++) printf("%c",s[i]); puts(""); } puts(""); } return 0; }