#include<stack>
#include<iostream>
#define MAXSIZE 100
using namespace std;
stack<int> s;
int main(){
char str[MAXSIZE];
while(cin>>str){
int i;
char ch;
for(i=0;str[i]!=0;i++){
if(str[i]=='('||str[i]=='['||str[i]=='{'){
s.push(str[i]);//将所有左括号的ascii码值入栈
}
else{
if(str[i]==')'||str[i]==']'||str[i]=='}'){
if(s.empty())
break;
else{
ch=s.top();
if((ch=='('&&str[i]==')')||(ch=='['&&str[i]==']')||(ch=='{'&&str[i]=='}'))
s.pop();//只有在匹配的时候才将括号栈的栈顶括号弹出
else
break;
}
}
}
}
if(str[i]==0&&s.empty())
cout<<"匹配成功"<<endl;//字符串内容全部处理完且括号栈为空
else
cout<<"匹配失败"<<endl;
}
return 0;
}
括号匹配
最新推荐文章于 2022-06-11 10:08:33 发布