栈-括号的匹配

// 判断输入的括号格式是否正确(只限于小括号和中括号)

【输入】

  [[([()])]]

【输出】

  YES


#include<iostream>
#include<cstring>
using namespace std;
char b[101];
int top=0;

void push(char x){
  if(top<101){
    top++;
    b[top]=x;
    return;
  }
  cout<<"进栈失败"<<endl;

}


void pop(){
  if(top>0){
    top--;
    return;
  }
  cout<<"出栈失败"<<endl;
}


int main(){
  char a[101];
  cin.getline(a,101);
  for(int i=0;i<strlen(a);i++){
    if(a[i]=='('||a[i]=='[') push(a[i]);
    else if(b[top]=='('&&a[i]==')') pop();
    else if(b[top]=='['&&a[i]==']') pop();
    else cout<<"NO"<<endl;
  }
  if(top==0)cout<<"YES"<<endl;
  return 0;
}

posted @ 2020-11-07 18:01  Hi,小董先生  阅读(48)  评论(0)    收藏  举报