C. Bracket Sequence
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
A bracket sequence is a string, containing only characters “(”, “)”, “[” and “]”.
A correct bracket sequence is a bracket sequence that can be transformed into a correct arithmetic expression by inserting characters “1” and “+” between the original characters of the sequence. For example, bracket sequences “()[]”, “([])” are correct (the resulting expressions are: “(1)+[1]”, “([1+1]+1)”), and “](” and “[” are not. The empty string is a correct bracket sequence by definition.
A substring s[l… r] (1 ≤ l ≤ r ≤ |s|) of string s = s1s2… s|s| (where |s| is the length of string s) is the string slsl + 1… sr. The empty string is a substring of any string by definition.
You are given a bracket sequence, not necessarily correct. Find its substring which is a correct bracket sequence and contains as many opening square brackets «[» as possible.
Input
The first and the only line contains the bracket sequence as a string, consisting only of characters “(”, “)”, “[” and “]”. It is guaranteed that the string is non-empty and its length doesn’t exceed 105 characters.
Output
In the first line print a single integer — the number of brackets «[» in the required bracket sequence. In the second line print the optimal sequence. If there are more than one optimal solutions print any of them.
Examples
inputCopy
([])
outputCopy
1
([])
inputCopy
(((
outputCopy
0
思路:将左括号下标压入栈,如果存在相应右括号,就将栈顶元素取出,这样栈中剩下的下标就是不匹配的下标,计算两个不匹配下标之间匹配的中括号个数就行了
#include<iostream>
#include <stack>
#include<map>
#include<cstring>
#include<cstdio>
using namespace std;
stack<int>s;
char a[100005];
int sum[100005];
int main()
{
// freopen("out.txt","r",stdin);
map<char,int>m;
m['(']=1;
m[')']=-1;
m['[']=2;
m[']']=-2;
scanf("%s",a);
sum[0]=(a[0]=='[');
int L=strlen(a);
for(int i=1;i<strlen(a);i++){//记录前i括号中'['个数的
sum[i]=sum[i-1]+(a[i]=='[');
}
for(int i=0;i<L;i++){
if(a[i]=='('||a[i]=='['||s.empty())
s.push(i);
else if(m[a[i]]+m[a[s.top()]]==0) //括号匹配,弹出栈顶元素
s.pop();
else s.push(i);
}
if(s.empty()){
int ans=0;
ans=sum[L-1];
cout<<sum[L-1]<<endl;
if(ans)
cout<<a<<endl;
}
else{
int ans=0;
int ss,e,ns,ne;
e=L-1;
if(sum[e]-sum[s.top()]>ans){
ans=sum[e]-sum[s.top()];
ns=s.top()+1;
ne=e;
}
while(s.size()>1){
e=s.top()-1;
// cout<<e<<endl;
s.pop();
ss=s.top();
if(sum[e]-sum[ss]>ans){
ans=sum[e]-sum[ss];
ns=ss+1;
ne=e;
}}
e=s.top();
if(s.top()>0)
e=e-1;
if(e==0)
{
sum[0]=0;
}
if(sum[e]>ans)
{
ans=sum[e];
ns=0;
ne=e;
}
if(ans){
cout<<ans<<endl;
for(int i=ns;i<=ne;i++){
printf("%c",a[i]);
}
cout<<endl;
}
else cout<<0<<endl;
}
}