#include <stdio.h>
#define MAX 100
int check (char *stack,int top,char n)
{
char &m=stack[top-1];
if (m=='<') return 0;
else if (m=='('&&n!='<') return 0;
else if (m=='['&&n!='<'&&n!='(') return 0;
else if (m=='{'&&n=='{') return 0;
else return 1;
}
int main()
{
int suc,i,top;
char a[MAX];
char stack[MAX];
while (scanf("%s",a)&&a[0]!='#')
{
top=0;suc=1;
for (i=0;suc&&a[i];i++)
{
if (a[i]=='<'||a[i]=='{'||a[i]=='['||a[i]=='(')
{
if (check(stack,top,a[i])) stack[top++]=a[i];
else suc=0;
}
else
{
if (a[i]=='>'&&stack[top-1]!='<') suc=0;
if (a[i]=='}'&&stack[top-1]!='{') suc=0;
if (a[i]==']'&&stack[top-1]!='[') suc=0;
if (a[i]==')'&&stack[top-1]!='(') suc=0;
top--;
}
}
if (suc&&top==0) printf("true\n");
else printf("false\n");
}
return 0;
}
加了检查嵌套顺序后,果然长长了,呵呵,这下应该可以了
[此贴子已经被作者于2007-3-21 12:59:03编辑过]