#include<stdio.h>
#include<stdlib.h>
#define N 100
//仿照栈进行存储左括号,与字符串内的数组进行对比
int main(int args,char *argv[])
{
char str[N];
char str1[N];
printf("input a new backet :\n");
gets(str);
int top=-1;
int i=0;
while(str[i]!='\0')
{
//左括号入"栈",
if(str[i]=='('||str[i]=='['||str[i]=='{')
{
++top;
str1[top]=str[i];
}
//右括号出"栈"
if(str[i]==')')
{
if(str1[top]=='(')
--top;
else
printf("缺少左小括号!");
}
if(str[i]=='}')
{
if(str1[top]=='{')
--top;
else
printf("缺少左大括号!");
}
if(str[i]==']')
{
if(str1[top]=='[')
--top;
else
printf("缺少左中括号!");
}
/*
if((str[i]==')'&&str1[top]=='(')||(str[i]==']'&& str1[top]=='[')||(str[i]=='}'&& str1[top]=='}'))
{
--top;
}
*/
i++;
}
if(top==-1)
{
printf("match successful!");
}
else
printf("wrong!");
system("pause");
return 0;
}
今天编写的一个代码,初始的时候没想出来,使用了switch 只是匹配左右括号的个数,引以为戒