【UVa 673】Parentheses Balance

Time Limit: 3000MS   Memory Limit: Unknown   64bit IO Format: %lld & %llu

 Status

Description

Download as PDF
 

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, () and [] 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<cstdio>
#include<cstring>
#include<stack>

using namespace std;

stack<char> st;
char s[1000];

bool check()
{
    for (int i = 0; i < strlen(s) - 1; ++i)
        if (s[i] == '(' || s[i] == '[') st.push(s[i]);
        else if (st.empty()) return false;
            else if ((st.top() == '(' && s[i] == ')') || (st.top() == '[' && s[i] == ']')) st.pop();
                else return false;
    return st.empty();
}

int main()
{
    int Test;
    scanf("%d", &Test);
    getchar();
    while (Test--)
    {
        fgets(s, 1000, stdin);
        while (!st.empty()) st.pop();
        if (check()) printf("Yes\n");
        else printf("No\n");
    }
    return 0;
}

 

posted @ 2015-10-04 09:29  albertxwz  阅读(288)  评论(0编辑  收藏  举报