给定一串字符,不超过100个字符,可能包括括号、数字、字母、标点符号、空格,编程检查这一串字符中的( ) ,[ ],{ }是否匹配。
输入格式:
输入在一行中给出一行字符串,不超过100个字符,可能包括括号、数字、字母、标点符号、空格。
输出格式:
如果括号配对,输出yes,否则输出no。
输入样例1:
sin(10+20)
输出样例1:
yes
输入样例2:
{[}]
输出样例2:
no
#include<stdio.h>
#include<string.h>
#define MaxSize 100
char str[101];
typedef enum {false, true} bool;
typedef struct SqStack{
char data[MaxSize];
int top;//栈顶指针
}SqStack;
void InitStack(SqStack *S);
void ReadChar();
bool bracketCheck(SqStack *S,char str[], int length);
bool Push(SqStack *S,char x);
bool StackEmpty(SqStack *S);
char Pop(SqStack *S);
int main()
{
SqStack S;//声明一个顺序栈
InitStack(&S);
ReadChar();
int length;
length = strlen(str);
bracketCheck(&S,str,length);
}
void InitStack(SqStack *S)
{
S->top = -1;
}
void ReadChar()
{
gets(str);
}
bool bracketCheck(SqStack *S,char str[], int length)
{
for(int i = 0; i<length; i++)
{
if(str[i]=='('||str[i]=='['||str[i]=='{')
Push(S,str[i]);//将左括号压入栈
else{
if(str[i]==')'||str[i]==']'||str[i]=='}')//扫描到右括号
{
if(StackEmpty(S)==true)//如果栈为空,则返回no
{
printf("no\n");
return false;
}
//不为空执行以下语句
char topElem;//栈顶元素
topElem = Pop(S);//栈顶元素出栈
if(str[i]==')'&&topElem!='(')
{
printf("no\n");
return false;
}
else if(str[i]==']'&&topElem!='[')
{
printf("no\n");
return false;
}
else if(str[i]=='}'&&topElem!='{')
{
printf("no\n");
return false;
}
}
}
}
if(StackEmpty(S)==true)
{
printf("yes\n");
return true;
}
else
{
printf("no\n");
return false;
}
}
bool Push(SqStack *S,char x)
{
S->top++;
S->data[S->top] = x;
return true;
}
bool StackEmpty(SqStack *S)
{
if(S->top == -1)
return true;
else
return false;
}
char Pop(SqStack *S)
{
char x;
x = S->data[S->top];
S->top--;
return x;
}