利用栈实现括号匹配算法

来源:互联网 发布:python手册中文版 pdf 编辑:程序博客网 时间:2024/06/05 04:02
#include<stdio.h>#include<stdlib.h>#include<string.h>#include<stack>using namespace std;#define OK 1#define ERROR 0int 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;}

原创粉丝点击