{}:yes
():yes
{([])}:yes
(]:no
…
/*括号匹配问题*/
#include <iostream>
#include <String.h>
using namespace std;
#define MaxSize 50
#define ElemType char
typedef struct {
ElemType data[MaxSize]={0};
int top;//栈顶“指针” 就指向栈顶元素,不是栈顶元素的下一位空白区域
}SqStack;
/*
从下标为0开始存储
栈空条件:S.top == -1
栈长:S.top+1
栈满条件:S.top == MaxSize-1
* */
//初始化
void InitStack(SqStack &S){
//要做的工作就是将栈空;
S.top=-1;
}
//判断栈空
bool StackEmpty(SqStack S){
return S.top == -1;
}
//进栈
bool Push(SqStack &S,ElemType x){
if(S.top==MaxSize-1)//如果栈满,返回false
return false;
S.data[++S.top]=x;
return true;
}
//出栈
ElemType Pop(SqStack &S){
if(S.top==-1)//栈空,无法出
return false;
ElemType x=S.data[S.top];
S.top--;
return x;
}
//打印
void show(SqStack S){
for(int i=0;i<=S.top;i++){
cout<<S.data[i]<<" ";
}
}
//读取栈顶元素,用x接受
ElemType GetTop(SqStack S, ElemType &x){
if(S.top==-1)
return -1;
x=S.data[S.top];
return x;
}
int main(){
SqStack S;
InitStack(S);
/*输入字符串,并将字符串放到字符数组中,
实现能够逐个扫描字符串中的字符,并且不跳过空格符
*/
string str;
getline(cin,str);
char ch[200]={'\0'};
strcpy(ch,str.c_str());
//flag标志 1匹配 0不匹配
int flag=1;
int i;
for(i=0;ch[i]!='\0';i++){
//元素为{ [ (入栈
if((ch[i] == '{' )|| (ch[i] =='[') || (ch[i] =='(')){
Push(S,ch[i]);
}//如果元素为) ] }出栈 赋值给a
else if(ch[i]=='}' || ch[i]==')' || ch[i]==']'){
char a=Pop(S);
if((a == '{' && ch[i] == '}') || (a == '(' && ch[i] == ')') || (a == '[' && ch[i] == ']')){
continue;
} else{
flag=0;
}
}
}
if(S.top != -1){ //当左括号多出没有与右括号匹配的时候(如:" {() " 此时栈不空
flag = 0;
}
if(flag == 0){
cout<<"no";
}else cout<<"yes";
return 0;
}
- Input&Output