用棧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;
}