#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;
}
利用栈实现括号匹配算法
最新推荐文章于 2023-09-21 21:21:01 发布