首页 > 改错——括号匹配判断算法
头像
牛客820579030号
编辑于 2020-07-17 23:00
+ 关注

改错——括号匹配判断算法

Description

假设在表达式中([]())或[([ ][ ])]等为正确的格式,[( ])或([( ))或 (( )])均为不正确的格式。基于栈设计一个判断括号是否正确匹配的算法。

Input

输入数据有多组,每组测试数据一行,一个字符串,只包含 ‘[‘ ,’]’ ,’(‘ ,‘)’ 。

Output

对于每组测试数据,若括号匹配输出yes,否则输出 no。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MaxSize 100

typedef struct
{
char data[MaxSize];
int top;
}SqStack;

void InitSqStack(SqStack &S)
{
S.top=-1;
}

bool Push(SqStack &S,char x)
{
if(S.top==MaxSize-1) return false;
S.data[++S.top]=x;
return true;
}

bool Pop(SqStack &S,char &x)
{
if(S.top==-1) return false;
x=S.data[S.top--];
return true;
}

bool StackEmpty(SqStack S)
{
if(S.top==-1) return true;
else return false;
}

bool IsOK(SqStack &S,char ch[])
{
int i=0;
char x;
for(i=0;i<strlen(ch);i++)
{
if(ch[i]=='('||ch[i]=='[')
{
Push(S,ch[i]);
}
else
{
if(ch[i]==')')
{
Pop(S,x);
if(x!='(') {return false;}
}
if(ch[i]==']')
{
Pop(S,x);
if(x!='[') {return false;}
}
}
}
return StackEmpty(S);
}

int main()
{
SqStack S;
char ch[100];
while(gets(ch)!=NULL)
{
InitSqStack(S);
if(IsOK(S,ch)) printf("yes\n");
else printf("no\n");
}
return 0;
}
为什么我这样写的代码一直报错?

全部评论

(0) 回帖
加载中...
话题 回帖

推荐话题

相关热帖

近期热帖

近期精华帖

热门推荐