Uva 673 Parentheses Balance

Uva 673 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

括号配对问题、使用栈。

首先判断字符串的长度,如果是奇数,肯定不配对。

其他情况的话,如果是’(‘或’[‘就进栈,如果是’)’或’]’就出栈,但出栈之前一定要判断栈是否为空,否则容易出问题的。当字符串读取完后,判断栈是不是空栈,如果是就输出Yes,

但是,有一点需要注意,“if it is the empty string”,说明在输入里可能会有空行,这就牵扯到用哪个输入问题了,如果用了scanf或cin,就会一直WA,getline和gets就ok了,是因为scanf和cin遇到空格都不处理

另外、切记Y是大写,es是小写 ╥﹏╥..
之前因为这个问题WA了很多次。


 #include <iostream>
 #include <cstdio>
 #include <stack>
 #include <string.h>
using namespace std;

int main()
{
 #ifndef  ONLINE_JUDGE
    freopen("1.txt", "r", stdin);
 #endif
    stack<char> s;
    int n, len;
    char a[150];
    bool flag;
    cin >> n;
    getchar();
    while (n--)
    {
        flag = true;
        gets(a);
        len = strlen(a);
        if (len % 2)
        {
            cout << "No" << endl;
            continue;
        }
        for (int i = 0; i < len; i++)
        {
            if (a[i] == '(' || a[i] == '[')
            {
                s.push(a[i]);
            }
            else if (!s.empty() && a[i] == ')')
            {
                if (s.top() == '(')
                {
                    s.pop();
                }
                else
                {
                    flag = false;
                    break;
                }
            }
            else if (!s.empty() && a[i] == ']')
            {
                if (s.top() == '[')
                {
                    s.pop();
                }
                else
                {
                    flag = false;
                    break;
                }
            }
            else 
            {
                flag = false;
            }
        }
        if (flag && s.empty())
        {
            printf("Yes\n");
        }
        else
        {
            printf("No\n");;
        }
        while(!s.empty())
        {
            s.pop();
        }
    }   
    return 0;
}

你可能感兴趣的:(栈,uva)