题目链接:http://acm.fzu.edu.cn/problem.php?pid=1411
题目描述:
Problem Description
给定由(,),[,],{,},<,>构成的一个括号字符串,输出它的一个最长子串,该子串有正确的括号配对。
Input
本题有多组输入数据,每组数据只有一行括号字符串,其长度不大于10000。
Output
对于每组数据,输出该括号字符串的最长配对子串。若答案不唯一,则输出最左边一个;如果答案不存在,则输出“No Solution”。
Sample Input
[()()]][]
Sample Output
[()()]
解题思路:考察栈的知识。
参考代码:
#include<iostream>
#include<string.h>
#include<stack>
using namespace std;
struct node
{
int pos;
char ch;
}Node[10010];
int main()
{
char s[10010];
int sign[10010];
int i;
int pos;
char ch;
while(cin>>s)
{
stack<node> sta;
memset(sign,0,sizeof(sign));
for(i=0; i<strlen(s); i++)
{
if(s[i]=='(' || s[i]=='[' || s[i]=='{' || s[i]=='<')
{
Node[i].ch = s[i];
Node[i].pos = i;
sta.push(Node[i]);
}
else
{
if(!sta.empty())
{
pos = sta.top().pos;
ch = sta.top().ch;
if(ch=='('&&s[i]==')' || ch=='['&&s[i]==']' || ch=='{'&&s[i]=='}' || ch=='<'&&s[i]=='>')
{
sign[i] = 1;
sign[pos] = 1;
sta.pop();
}
else
{
Node[i].ch = s[i];
Node[i].pos = i;
sta.push(Node[i]);
}
}
}
}
while(!sta.empty())
sta.pop();
int begin,end,max=0;
for(i=0; i<strlen(s); i++)
{
if(sign[i]==0) continue;
else
{
int j=i;
int temp = 0;
while(sign[j] == 1)
{
temp ++;
j++;
}
if(temp > max)
{
begin = i;
end = j-1;
max = temp;
}
i = j-1;
}
}
if(max != 0)
{
for(i=begin; i<=end; i++)
cout<<s[i];
}
else
cout<<"No Solution";
cout<<endl;
}
return 0;
}