括号匹配问题
1000(ms)
65535(kb)
2793 / 11822
假设表达式中允许包含两种括号:圆括号和方括号。编写一个算法判断表达式中的括号是否正确配对。
输入
由括号构成的字符串,包含”(“、”)“、”[“和”]“。
输出
如果匹配输出YES,否则输出NO。
样例输入
[([][]())]
样例输出
YES
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
#include<string.h>
char a[100];
//链栈
typedef struct linknode{
char data;
linknode *next;
}LinkNode;
void init(LinkNode *&L){
L=(LinkNode *)malloc(sizeof(LinkNode));
L->next=NULL;
}
void push(LinkNode *&L,char data){
LinkNode *head;
head=L;
LinkNode *s;
s=(LinkNode *)malloc(sizeof(LinkNode));
s->data=data;
s->next = L->next;
L->next=s;
}
bool pop(LinkNode *&L,char &data){
if(L->next==NULL)
return false;
LinkNode *p;
p=L->next;
data=p->data;
L->next=p->next;
free(p);
}
void judge(LinkNode *&L,char a[],int length){
int i=0;
while(i<length){
char character;
if(a[i]=='('||a[i]=='['){
push(L,a[i]);
}
else if(a[i]==')')
{
pop(L,character);
if(character!='(')
{
printf("NO");
return;
}
}
else if(a[i]==']')
{
pop(L,character);
if(character!='[')
{
printf("NO");
return;
}
}
i++;
}
if(L->next==NULL)
{
printf("YES");
}else
{
printf("No");
}
}
int main()
{
scanf("%s",&a);
int length=strlen(a);
LinkNode *L;
init(L);
judge(L,a,length);
return 0;
}