描述:
给出一个仅包含字符'(',')','{','}','['和']',的字符串,判断给出的字符串是否是合法的括号序列括号必须以正确的顺序关闭,"()"和"()[]{}"都是合法的括号序列,但"(]"和"([)]"不合法。
输入样例1
[
输出样例1
false
输入样例2
()
输出样例2
true
Code:
#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
typedef struct
{
char *top;
char *base;
int Stacksize;
}sqStack;
void InitStack(sqStack *s)
{
s->base=malloc(STACK_INIT_SIZE*sizeof(char));
s->Stacksize=STACK_INIT_SIZE;
s->top=s->base;
*s->top++='#';
}
void Push(sqStack *s,char ch)//假设不会栈满栈空
{
*s->top++=ch;
}
void Pop(sqStack *s,char *ch)
{
*ch=*--s->top;
}
int main()
{
char ch,temp;
sqStack s;
InitStack(&s);
while((ch=getchar())!=EOF)
{
if(ch=='('||ch=='['||ch=='{')
{
Push(&s,ch);
}
else if(ch==')'||ch==']'||ch=='}')
{
Pop(&s,&temp);
if((ch!=(temp+1))&&(ch!=(temp+2)))
{
NO: printf("false");
return 0;
}
}
}
Pop(&s,&temp);
if(temp=='#')
{
printf("true");
}
else
{
goto NO;
}
return 0;
}