括号匹配的问题我们让他遇到左括号就进栈遇到右括号判断栈是否为空如果空就不可能匹配不为空就判断是否可以相等不相等就加一然后出栈
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
#include<cstdio>
#include<stack>
using namespace std;
char str[1000011];
int main(){
scanf("%s",str);
int i=0;
stack<char>cnt;
int cns=0;
bool k=true;
while(str[i]){
if(str[i]=='['||str[i]=='('||str[i]=='{'||str[i]=='<'){
cnt.push(str[i]);
}
if(str[i]==']'||str[i]==')'||str[i]=='}'||str[i]=='>'){
if(cnt.empty()){
k=false;
break;
}
else{
if( !( (str[i]==']'&&cnt.top()=='[') || (str[i]=='}'&&cnt.top()=='{')||(str[i]==')'&&cnt.top()=='(')||(str[i]=='>'&&cnt.top()=='<') ) )
cns++;
cnt.pop();
}
}
i++;
}
if(cnt.empty()&&k)
printf("%d\n",cns);
else
printf("Impossible\n");
return 0;
}