您的位置:首页 > 其它

利用栈实现括号匹配算法

2013-08-17 16:36 405 查看
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
using namespace std;

#define OK 1
#define ERROR 0

int parent_match(char *s,int len)
{
stack<char> st;
int e;
while(*s)
{
switch(*s)
{
case '(':
case '[':st.push(*s++);
break;
case ')':
case ']':if(!st.empty())
{ //一定要判断,否则下面有st.pot,如果栈空,st.pop()就会出错,
//会出现deque iterator not dereferencable这种蛋疼的错误
e = st.top();
if(  *s == ')' && e!='(' || *s==']' && e!='[' )
return ERROR;
else
{
st.pop();
s++;
break;
}
}
else
{
printf("缺少左括号\n");
return ERROR;
}
default: s++;
}
}

if(st.empty())
return OK;
else
return ERROR;
}

int main()
{
char *str = "5+6*((3+4))+[(2-1)*(1*3)]+[]+(";
int len = strlen(str);
int result = 0;
result = parent_match(str,len);
if(result)
printf("括号匹配\n");
else
printf("括号不匹配\n");
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: