uvaoj 673 Parentheses Balance

来源:互联网 发布:净网行动知乎 编辑:程序博客网 时间:2024/06/11 09:44

  方法都能想到,就是用栈实现括号匹配嘛!

  WA了4次,总结了3个需要注意的地方

①.就是题目说的若输入为空行,也属于Yes的情况。所以需要用fgets()

②.当栈为空时,此时读到 ] 或 ),此时应该跳出,但是top为零,注意不要也输出Yes,所以添加了一个标志变量OK

③.注意要每次初始化OK与top的值。

#include<stdio.h>#include<string.h>char stack[150];int main(){    int n,top;    scanf("%d",&n);    getchar();    while(n--)    {        char s[150];        int ok=0;        fgets(s,sizeof(s),stdin);        top=0;        for(int i=0;s[i]!='\n';i++)        {            if(s[i]=='('||s[i]=='[')  stack[++top]=s[i];            else            {                if(top==0)  {ok=1;break;}                else if((stack[top]=='['&&s[i]==']')||(stack[top]=='('&&s[i]==')'))  top--;                else  break;            }        }        if(top==0&&ok!=1)   printf("Yes\n");        else   printf("No\n");    }    return 0;}


0 0
原创粉丝点击