ZOJ2704(Brackets)
Given a string consisting of brackets of two types find its longest substring that is a regular brackets sequence.
Input
There are mutiple cases in the input file.
Each case contains a string containing only characters ‘(’ , ‘)’ , ‘[’ and ‘]’ . The length of the string does not exceed 100,000.
There is an empty line after each case.
Output
Output the longest substring of the given string that is a regular brackets sequence.
There should be am empty line after each case.Sample Input
([(][()]]() ([)]
Sample Output
[()]
//2009-05-11 18:21:20 Accepted 2704 C++ 60 776
#include <iostream>
#include <stack>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 100004;
typedef struct
{
char data;
int pos;
}node;
char str[N];
bool pp[N];
bool isok(char a, char b)
{
if(a == '(' && b == ')')
return true;
if(a == '[' && b== ']')
return true;
return false;
}
void solve()
{
stack<node> S;
node a;
int len = strlen(str);
int i , j, k, s, e;
int maxp, tmp;
////////////////////////////////
memset(pp, false, sizeof(pp));
for(i = 0; i < len; i++)
{
if(str[i] == '(' || str[i] == '[')
{//对于左括号,入栈
a.data = str[i]; a.pos = i;
S.push(a);
}
else
{
if(S.size())
{//栈非空情况
a = S.top();
if(isok(a.data, str[i]))
{//匹配情况
S.pop();
pp[a.pos] = true;
pp[i] = true;
}
else
{
a.data = str[i];
a.pos = i;
S.push(a);
}
}
else
{
a.data = str[i];
a.pos = i;
S.push(a);
}
}
}
maxp = 0;
i = 0;
while(i < len)
{
while(pp[i] == false && i < len)
i++;
if(i >= len)
break;
j = i; tmp = 0;
while(pp[i] && i < len)
i++;
k = i - 1;
if(k - j > maxp)
{
maxp = k - j;
s = j; e = k;
}
}
if(maxp)
{
while(s <= e)
printf("%c", str[s++]);
}
printf("\n\n");
}
int main()
{
while(scanf("%s", str) != EOF)
{
solve();
}
return 0;
}
#include <iostream>
#include <stack>
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 100004;
typedef struct
{
char data;
int pos;
}node;
char str[N];
bool pp[N];
bool isok(char a, char b)
{
if(a == '(' && b == ')')
return true;
if(a == '[' && b== ']')
return true;
return false;
}
void solve()
{
stack<node> S;
node a;
int len = strlen(str);
int i , j, k, s, e;
int maxp, tmp;
////////////////////////////////
memset(pp, false, sizeof(pp));
for(i = 0; i < len; i++)
{
if(str[i] == '(' || str[i] == '[')
{//对于左括号,入栈
a.data = str[i]; a.pos = i;
S.push(a);
}
else
{
if(S.size())
{//栈非空情况
a = S.top();
if(isok(a.data, str[i]))
{//匹配情况
S.pop();
pp[a.pos] = true;
pp[i] = true;
}
else
{
a.data = str[i];
a.pos = i;
S.push(a);
}
}
else
{
a.data = str[i];
a.pos = i;
S.push(a);
}
}
}
maxp = 0;
i = 0;
while(i < len)
{
while(pp[i] == false && i < len)
i++;
if(i >= len)
break;
j = i; tmp = 0;
while(pp[i] && i < len)
i++;
k = i - 1;
if(k - j > maxp)
{
maxp = k - j;
s = j; e = k;
}
}
if(maxp)
{
while(s <= e)
printf("%c", str[s++]);
}
printf("\n\n");
}
int main()
{
while(scanf("%s", str) != EOF)
{
solve();
}
return 0;
}