发表文章

[最新] Parentheses Balance(出入栈)

sadsummerholiday 3月前 102

Parentheses Balance

                                                                                                                                      UVA - 673 

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

题一看就是栈的应用,借此复习STL中的STACK,但写的时候耗费了我好多时间,主要是一些基本功的问题,注意一下:

1.cin取不到空格,读入的全是内容,必须用scanf来读入换行和空格
2.每次用栈顶前,先判断是否empty(),考虑初始的特殊情况
3.()、【】不能直接相等啊!!用了好大时间才想起来,分情况一一对应才可以

4.stack没有clear(),要用while循环不断pop(),知道。empty()



#include<stack>
#include<stdio.h>
#include<cstring>
#include<iostream>
using namespace std;

int main()
{
    stack<char> s;
    char t,temp;
    int n;
    scanf("%d",&n);
    scanf("%c",&t);
    while(n--)
    {
        while(scanf("%c",&t))
        {
             if(!s.empty())
             {
                 temp=s.top();

             }
             ;
             if(t=='\n')
              {
                if(!s.empty())
                    {
                        cout<<"No\n";
                        while(!s.empty())
                            s.pop();
                        break;
                    }
                else
                {
                    cout<<"Yes\n";
                    while(!s.empty())
                            s.pop();
                            break;
                }

              }
            else if(!s.empty()&&t==')'&&temp=='(')
            {
                s.pop();

            }
            else if(!s.empty()&&t==']'&&temp=='[')
            {
                s.pop();

            }
            else
            {
                s.push(t);
            }
        }
    }

    return 0;
}

//1.cin娶不到空格,必须sacnf
//2.每次用站顶前,啊【判断是否empty
//3.()、【】不能直接相等啊
//4.stack没有clear,同while循环pop

相关推荐
最新评论 (0)
返回
发表文章
sadsummerholiday
文章数
52
评论数
0
注册排名
1307071