基于栈的简单括号匹配

来源:互联网 发布:淘宝网电影票团购 编辑:程序博客网 时间:2024/06/05 10:11
#include<iostream>#include<stack>using namespace std;int pipei(char *str){int index=0;char c;stack<char> s;s.push('#');//作为最后一个#的匹配while((c=str[index++])!='\0'){switch(c){case '{':s.push(c);break;case '}':if(s.top()=='{')s.pop();else {cout<<index<<"的位置上的'}'不匹配与前面的字符'"<<s.top()<<"'不匹配"<<endl; return 0;}break;case '[':s.push(c);break;case ']':if(s.top()=='[')s.pop();else {cout<<index<<"的位置上的']'不匹配与前面的字符'"<<s.top()<<"'不匹配"<<endl; return 0;}break;case '(':s.push(c);break;case ')':if(s.top()=='(')s.pop();else {cout<<index<<"的位置上的')'不匹配与前面的字符'"<<s.top()<<"'不匹配"<<endl; return 0;}break;case '#':if(s.top()=='#') s.pop();else {cout<<index<<"的位置上的'#'不匹配与前面的字符'"<<s.top()<<"'不匹配"<<endl; return 0;}break;}}cout<<"括号匹配完成"<<endl;return 1;}int main(){stack<char> s;char *str="{[()}]}#";//以#为结束条件pipei(str);system("pause");return 0;}

原创粉丝点击