下面的程序使用stack实现了括号匹配的检验:
#include<iostream>
#include<stack>
#include<string.h>
using namespace std;
#define N 1000
char str[N];
int main(){
cin>>str;
int len=strlen(str);
stack<char> st;
int i;
int t=0;
for(i=0;i<len;++i){
if(str[i]=='('||str[i]=='[')
st.push(str[i]);
else{
if(str[i]==')'){
if(st.top()!='('){
t=1;
break;
}
st.pop();
}
if(str[i]==']'){
if(st.top()!='['){
t=1;
break;
}
st.pop();
}
}
}
if(t==1||!st.empty())
cout<<"不匹配"<<endl;
else
cout<<"匹配"<<endl;
return 0;
}
转载于:https://blog.51cto.com/beyond316/1256061