C++中使用STL模板对括号进行匹配

#include<iostream>
#include<cstdio>
#include<iomanip>
#include<cstring>
#include<stack>
using namespace std;
//创建空栈 
stack<int> s;
char a[100];
int main(){
    cin>>a;
    int l=strlen(a);
    for(int i=0;i<l;i++){
        //将左边的括号进行进栈操作 
        if(a[i]=='('||a[i]=='['){
            s.push(a[i]);
        }else if(a[i]==')'&&s.top()=='('){
            s.pop();
        }else if(a[i]==']'&&s.top()=='['){
            s.pop();
        }else{
            cout<<"NO";
            return 0;
        }
    }
    if(s.empty()){
        cout<<"YES";
    }else{
        cout<<"NO";
    }
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/qq_37651894/article/details/97822347