Uva 673 Parentheses Balance

来源:互联网 发布:淘宝网正品手提包女 编辑:程序博客网 时间:2024/06/15 11:06

链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=614

题意:栈的问题。判断括号是否正确匹配,注意第一个条件,字符串为空也为正确,这点坑了好久。

//此题注意a条件 空字符串为'\0'或'\n'#include <stdio.h>#include <iostream>#include <stack>#include <string.h>using namespace std;const int m = 500;int main(){    int t;    char stack[m];    char a[m];    cin >> t;    getchar();//吃掉输入t时的'\n';    memset(stack,'\0',sizeof(stack));    memset(a,'\0',sizeof(a));    while(t--)    {        gets(a);        int l=strlen(a);        int top=1;        int ok=1;        stack[top]=a[0];        int i=1;        if(a[0]=='\0'||a[0]=='\n')//字符串为空输出;        {            cout << "Yes" << endl;            continue;        }        while(i<l)//字符串不为空进行判断        {            if(a[i]==')')            {                if(stack[top]=='[')                {                    ok=0;break;                }                if(stack[top]=='(')                {                    top--;                    i++;                    continue;                }            }            if(a[i]==']')            {                if(stack[top]=='(')                {                    ok=0;break;                }                if(stack[top]=='[')                {                    top--;                    i++;                    continue;                }            }            if(a[i]=='[')            {                stack[++top]=a[i];                i++;                continue;            }            if(a[i]=='(')            {                stack[++top]=a[i];                i++;                continue;            }            stack[++top]=a[i];            i++;        }        if(ok&&top==0)        {            printf("Yes\n");        }        else            printf("No\n");    }}


0 0
原创粉丝点击