匹配括号&栈

#include <iostream>
#include <stack>
using namespace std;
int main(){
	string a;
	stack<char> s;
	cin>>a;
	for(int i=0;i<a.length();i++){
		if(a[i]=='(' || a[i]=='[' || a[i]=='{'){
			s.push(a[i]);
		}
		if(a[i]==')'||a[i]==']'||a[i]=='}'){
			if(s.top()=='('&&a[i]==')' || s.top()=='['&&a[i]==']' || s.top()=='{'&&a[i]=='{'){
				s.pop();
			}else{
				cout<<"false"<<endl;
				return 0;
			}
		}
	}
	if(s.empty()){
		cout<<"true"<<endl;
	}
	return 0;
}

  

posted @ 2024-02-19 11:43  fushuxuan1  阅读(10)  评论(0)    收藏  举报