数据结构07——表达式括号匹配

    xiaoxiao2022-07-13  165

    Description 假设一个算术表达式中可以包含三种括号:圆括号“( ”和“ )”、方括号“ [ ”和“ ] ”和花括号“{”和“}”,且这三种括号可按任意的次序嵌套使用(如:…[…{…}…[…]…]…[…]…(…)…)。编写判别给定表达式中所含括号是否正确配对出现的程序(已知表达式已存入数据元素为字符的顺序表中)。

    Input 输入算术表达式,换行结束。

    Output 若给定表达式中所含括号正确配对,则输出yes,否则输出no。

    样例输入:

    [5+(6-3)]-(2+3)]

    样例输出:

    no #include <iostream> #include <stack> #include <cstdio> #include <cstring> using namespace std; int match(string str){ int i,flag=0; stack<char> s; char t; int len=str.length(); for(i=0;i<len;i++){ if(str[i]=='['||str[i]=='{'||str[i]=='('){ s.push(str[i]); } if(str[i]==']'||str[i]=='}'||str[i]==')'){ if(s.empty()) return 1; else{ if(str[i]==']'){ t=s.top(); if(t=='[') s.pop(); else return 1; } if(str[i]=='}'){ t=s.top(); if(t=='{') s.pop(); else return 1; } if(str[i]==')'){ t=s.top(); if(t=='(') s.pop(); else return 1; } } } } if(!s.empty()) return 1; if(s.empty()&&flag!=1) return 0; } int main() { string str; cin>>str; int flag=match(str); if(flag==0) cout<<"yes"<<endl; else cout<<"no"<<endl; }

     

    最新回复(0)