所在位置:论坛首页 -> 计算机科学与技术 -> 程序设计 -> [原创][求助]谁能帮我看看,我这个算法的缺陷? |
这是一个判断括号匹配问题的算法,当输入{]这样的括号时,判断结果却是括号匹配,但是当输入比如{}{}{}[],或者其它不匹配的时候都能正确判断。哪错了,帮看看。
#include<iostream>
using namespace std;
const char MAX_SIZE=100;
class SeqStack
{
public:
SeqStack ( ){top=-1;} ;
~SeqStack ( ){};
void Push ( char x );
char Pop ( );
bool Empty ( );
private:
char data[MAX_SIZE];
int top;
};
void SeqStack::Push ( char x)
{
if (top==MAX_SIZE-1)
throw "溢出";
top++;
data[top]=x;
}
char SeqStack:: Pop ( )
{ char x;
if (top==-1) throw "溢出";
x=data[top--];
return x;
}
bool SeqStack::Empty()
{
if(top==-1) return 1;
else return 0;
}
void main()
{
SeqStack s;
int a;
cout<<"输入需要判断的内容:"<<endl;
char p[100];
for(int j=0;j<100;j++)
{p[j]='\0';}
cin.getline(p,100,'\n');
a=strlen(p);
int t=0;
for(int i=0;i<a;++i)
{
static char y=0;
if(((p[i]=='[')|(p[i]=='{')|(p[i]=='(')))
{
y=p[i];
j++;
s.Push(p[i]);t++;
}
else if(((y &&p[i])==('['&&']'))||((y &&p[i])==('{'&&'}'))||((y &&p[i])==('('&&')' )))
{s.Pop();y=0;}
else break;
}
if(s.Empty())
{
if(p[0]==']'||p[0]=='}'||p[0]==')'||p[0]=='\0')
{cout<<"无法匹配:"<<endl;}
else if(a==t*2)
{cout<<"符合条件:"<<endl;}
}
else
{cout<<"无法匹配:"<<endl;}
}
请将
else if(((y &&p[i])==('['&&']'))||((y &&p[i])==('{'&&'}'))||((y &&p[i])==('('&&')' )))
改为:
else if((y=='['&&p[i]==']')||(y =='{'&&p[i]=='}')||(y=='('&&p[i]==')'))
即可.
这个匹配的条件和逻辑以及 && 的作用要弄明白.
谢谢!
操作选项: 评分 加精 解精 奖惩 设专题 设公告 解公告 固顶 总固顶 解固顶 结帖 解结帖 锁帖 解锁 移帖 删帖 |
|