用栈ADT应用:对称符号匹配判断
输入一行符号,以#结束,判断其中的对称符号是否匹配。对称符号包括:
{ } 、 [ ] 、 ( )、 < >
输出分为以下几种情况:
(1)对称符号都匹配,输出 “ right. “
(2) 如果处理到最后出现了失配,则输出两行:
第一行:Matching failure.
第二行:loss of right character $$.... 其中$$... 是按嵌套顺序对应的右匹配符号。
(3)处理到某个符号时失配了,则输出两行或三行:
第一行: The N character '$' is wrong." ,其中N是出错符号的序号,$是出错的符号;
第二行: loss of left character $.” 其中 $ 是当前符号的左匹配符号。
(如果有的话)第三行:loss of right character $$...” 其中$$... 是按嵌套顺序对应的右匹配符号。
例如:
输入
(a.b)>#
输出:
The 6 character >’ is wrong.
loss of left character <.
输入 :
({()#
输出:
Matching failure.
loss of right character }).
例如:
输入 Result
as(*x<{(({<>}))}>)#
right.
(a.b)>#
The 6 character ‘>’ is wrong.
loss of left character <.
主要是注意第三种情况
给一组样例
{{{)
The 4 character ')' is wrong.
loss of left character (.
loss of right character }}}.
#include <cstdio>
#include <cstring>
#include <cmath>
#include <stack>
#include<iostream>
using namespace std;
char stander[2][4]= {'(','[','{','<',')',']','}','>'};
int main()
{
char s[1000]="";
stack<char> sta;
scanf("%s",s);
int len=strlen(s);
int sign=1;
int i;
for(i=0; i<len; i++)
{
if(s[i]=='('||s[i]=='{'||s[i]=='['||s[i]=='<')
sta.push(s[i]);
if(s[i]==')'||s[i]=='}'||s[i]==']'||s[i]=='>')
{
if(sta.empty())
{
printf("The %d character '%c' is wrong.\n",i+1,s[i]);
for(int j=0; j<4; j++)
if(s[i]==stander[1][j])
printf("loss of left character %c.\n",stander[0][j]);
sign=0;
break;
}
char c=sta.top();
int note=1;
for(int j=0; j<4; j++)
{
if(c!=stander[0][j]&&s[i]==stander[1][j])
{
note=0;
printf("The %d character '%c' is wrong.\n",i+1,s[i]);
printf("loss of left character %c.\n",stander[0][j]);
sign=0;
break;
}
}
if(note)
sta.pop();
if(!sign)
break;
}
}
if(!sign)
{
if(!sta.empty())
{
printf("loss of right character ");
while(!sta.empty())
{
char p=sta.top();
sta.pop();
for(int k=0; k<4; k++)
{
if(stander[0][k]==p)
cout<<stander[1][k];
}
}
cout<<'.'<<endl;
}
return 0;
}
int flag=0;
if(sign&&!sta.empty())
cout<<"Matching failure.\nloss of right character ",flag=1;
while(sign&&!sta.empty())
{
char c=sta.top();
sta.pop();
for(int i=0; i<4; i++)
{
if(stander[0][i]==c)
cout<<stander[1][i];
}
}
if(flag)
cout<<'.'<<endl;
else if(sign)
cout<<"right."<<endl;
return 0;
}