用栈来做比较简单,直接使用STL中的stack。
是左括号入栈,是右括号进行判断:
若栈顶元素是匹配的左括号,则出栈;否则,直接返回不匹配。
其它元素不管,跳过。
<span style="color:#ff0000;">注意:stack.top();stack.pop()的前提是stack.empty()==false;即栈不为空</span>
#include <iostream>
#include <stack>
#include <algorithm>
using namespace std;
stack<char> st;
int Check(char *p)
{
int len=strlen(p);
for(int i=0;i<len;i++)
{
if(p[i]=='('||p[i]=='['|| p[i]=='{')//是左括号的入栈
{
st.push(p[i]);
}
if(p[i]==')')//是右括号 判断
{
if( !st.empty() && st.top()=='(')//匹配,出栈。注意:top(),pop()时要不为空,否则出错
{
st.pop();
}
else
return 0;//不匹配,则直接返回
}
if(p[i]==']')
{
if( !st.empty() && st.top()=='[')
{
st.pop();
}
else
return 0;
}
if(p[i]=='}')
{
if( !st.empty() && st.top()=='{')
{
st.pop();
}
else
return 0;
}
}
if(st.empty()==true)//栈为空了,说明匹配;否则,不匹配
{
return 1;
}
else
return 0;
}
void main()
{
char p[100];
cin>>p;
int r=Check(p);
if(r==1)
cout<<"正确"<<endl;
else
cout<<"错误"<<endl;
system("pause");
}