SDUTOJ 2134--括号匹配

从前往后遍历字符串,当遇到左括号时进栈,遇到右括号时先判断栈是否为空,若为空,则输出no,继续下一循环;若不为空,看栈顶元素是否和其匹配,若匹配,则删掉栈顶元素,继续往后遍历字符串。最后若栈为空,则匹配完全,输出yes,否则输出no。

#include 
#include 

char st[55];
char stac[55];

int main()
{
    int i;

    while(gets(st)!=NULL)
    {
        int top=0;
        int flag=0;

        for(i=0;st[i]!='\0';i++)
        {
            if(st[i]=='('||st[i]=='['||st[i]=='{')
               stac[top++]=st[i];
            else if(st[i]==')'||st[i]==']'||st[i]=='}')
            {
                if(top==0)
                {
                    flag=1;
                    printf("no\n");
                    break;
                }else
                {
                    if((st[i]==')'&&stac[top-1]=='(')||(st[i]==']'&&stac[top-1]=='[')||(st[i]=='}'&&stac[top-1]=='{'))
                     top--;
                }
            }
        }

        if(flag)        //因为前面也是top=0时输出的no,若没有这句,会再次输出yes.
        continue;
        if(top==0)
        printf("yes\n");
        else
        printf("no\n");
    }

    return 0;
}

你可能感兴趣的:(栈和队列)