思路:用栈的方法解决,左括号入栈,右括号判断栈顶元素是否与之匹配,最后结束时判断栈是否为空,因为合法序列元素最后一定可以完全出栈
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
bool judge(char * s){
int top=0;
int len=0;
int i=0;
len=strlen(s);
char *stack=(char *)malloc(sizeof(char)*((len+1)/2));
for(i=0;i<len;i++){
if(s[i]=='['||s[i]=='('||s[i]=='{')
{
stack[++top]=s[i];
}
if(s[i]==']'){
if(stack[top]=='[')
{
top--;
}
else
return false;
}
if(s[i]==')'){
if(stack[top]=='(')
{
top--;
}
else
return false;
}
if(s[i]=='}'){
if(stack[top]=='{')
{
top--;
}
else
return false;
}
}
if(top!=0){
free(stack);
return false;
}
else{
free(stack);
return true;
}
}
int main()
{
char str[100];
gets(str);
int a;
a = judge(str);
if(a)
printf("true");
else
printf("false");
}