匹配括号&栈

 

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

  

posted @ 2024-02-19 11:31  王ys  阅读(6)  评论(0编辑  收藏  举报