用栈实现:输入一行符号,以#结束,判断其中的括号是否匹配。括号包括:
{ } 、 [ ] 、 ( )、 < >
如果匹配,输出 right
如果不匹配,给出错误提示。包括:
(1)对称符号都匹配,输出 “ right “
(2)处理到某个符号时不匹配了,输出 " The $ character '*' is wrong." ,其中$是出错符号的序号,*是出错的符号;
(3)如果有没匹配的左符号,输出缺失的对应的右符号,即输出 “loss of right character 。。。.”,其中。。。是按嵌套顺序对应的右符号。
例如:
输入 |
Result |
as(*x<{(({<>}))}>)#
|
right
|
(a.b)>#
|
The 6 character '>' is wrong. |
({()# |
loss of right character }). |
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int cnt=0;
char a[1000];
bool flag=false;
class SeqStack{
public :
int *a;
int top;
public:
SeqStack()
{
a=new int[105];
top=-1;
}
void Push(int x)
{
a[++top]=x;
}
void Pop()
{
top--;
}
bool Empty()
{
if(top==-1) return true;
return false;
}
int Top()
{
return a[top];
}
};
void Judge(string str) //使用栈判断括号匹配
{
//stack <char>s;
SeqStack s;
int i=0;
while(str[i]!='#')
{
switch (str[i])
{
case '(':
s.Push('(');
break;
case '[':
s.Push('[');
break;
case '<':
s.Push('<');
break;
case '{':
s.Push('{');
break;
case ')':
if(!s.Empty())
{
if (s.Top() == '(')
{
s.Pop();
}
else
{
a[cnt]=s.Top();
cnt++;
}
}
else
{
//s.push(')');
cout<<"The "<<i+1<<" character"<<" '"<<str[i]<<"' is wrong."<<endl;
flag=true;
}
break;
case '>':
if(!s.Empty())
{
if (s.Top() == '<')
{
s.Pop();
}
else
{
a[cnt]=s.Top();
cnt++;
}
}
else
{
//s.push('>');
cout<<"The "<<i+1<<" character"<<" '"<<str[i]<<"' is wrong."<<endl; flag=true;
}
break;
case ']':
if(!s.Empty())
{
if (s.Top() == '[')
{
s.Pop();
}
else
{
a[cnt]=s.Top();
cnt++;
}
}
else
{
//s.push(']');
cout<<"The "<<i+1<<" character"<<" '"<<str[i]<<"' is wrong."<<endl; flag=true;
}
break;
case '}':
if(!s.Empty())
{
if (s.Top() == '{')
{
s.Pop();
}
else
{
a[cnt]=s.Top();
cnt++;
}
}
else
{
cout<<"The "<<i+1<<" character"<<" '"<<str[i]<<"' is wrong."<<endl;
}
break;
}
i++;
}
if (s.Empty()&& flag==false)
{
cout<<"right"<<endl;
}
else if(!s.Empty())
{
cout<<"loss of right character ";
while(!s.Empty())
{
if(s.Top()=='<') cout<<">";
if(s.Top()=='(') cout<<")";
if(s.Top()=='{') cout<<"}";
if(s.Top()=='[') cout<<"]";
s.Pop();
}
cout<<'.'<<endl;
}
if(cnt)
{
cout<<"loss of right character ";
for(int i=0; i<cnt; i++)
{
cout<<a[i];
}
cout<<endl;
}
}
int main()
{
string str;
cin >> str;
Judge(str);
// system("pause");
return 0;
}