Fork me on GitHub

Uva 673 - Parentheses Balance

Parentheses Balance 

You are given a string consisting of parentheses () and []. A string of this type is said to be correct:

(a)
if it is the empty string
(b)
if A and B are correct, AB is correct,
(c)
if A is correct, (A) and [A] is correct.

Write a program that takes a sequence of strings of this type and check their correctness. Your program can assume that the maximum string length is 128.

 

Input 

The file contains a positive integer n and a sequence of n strings of parentheses () and [], one string a line.

 

Output 

A sequence of Yes or No on the output file.

 

Sample Input 

 

3
([])
(([()])))
([()[]()])()

 

Sample Output 

Yes
No
Yes

 

 


Miguel Revilla 
2000-08-14
 
 
#include<stdio.h>
#include<string.h>
int main()
{
    char pipei[130], temp[130];
    int i, front, rear, len, n, flag;
    scanf("%d", &n);
    getchar();
    while(n--)
    {
        memset(pipei, '\0', sizeof(pipei));
        memset(temp, '\0', sizeof(temp));
        rear = front = 0;
        fgets(temp, 130, stdin);
        len = strlen(temp);
        if(temp[len-1] == '\n') len--;
        flag = 0;
        for(i=0; i<len; ++i)
        {
            if(temp[i] == ' ') continue;
                if(temp[i] == '(' || temp[i] == '[')    pipei[rear++] = temp[i];
                else
                {
                    if(temp[i] == ')')
                    {
                        if(rear > 0 && pipei[--rear] == '(')
                        {
                            pipei[rear] = '\0';
                        }
                        else {flag = 1; break;}
                    }
                    else 
                    {
                        if(rear > 0 && pipei[--rear] == '[')
                        {
                            pipei[rear] = '\0';
                        }
                        else {flag = 1; break;}
                    }
                }
        }
        if(flag || rear != front) printf("No\n");
        else printf("Yes\n");
    }
    
    return 0;
} 

 

解题报告:

括号匹配,很早之前做过的,没想到这次做竟然会WA,其中一个原因是没有考虑到只输入一个回车的问题,还有就是思维不够严谨,中间判断的时候出了篓子。

posted @ 2012-11-30 13:01  Gifur  阅读(881)  评论(0编辑  收藏  举报
TOP