ACM 之 D - Parentheses Balance

Description

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",否则"No".
需要注意的是 , 如果什么都不输入的话,也要输出"Yes" , 这也是这一题的难点.

代码部分

#include<iostream>
#include<string.h>
#include<string>
#include<stack>
using namespace std;
string s;    const char *s1;    double j;
stack<char>x;
stack<char>y;
int main()
{
    int n;
    cin>>n;
    getchar();
    while(n--)
    {
        getline(cin,s);
        if(s.size()==0)
            {cout<<"Yes\n";continue;}
        while(!x.empty())
        {
            x.pop();
        }
        while(!y.empty())
        {
            y.pop();
        }
        s1=s.c_str();
        char *s2=new char[strlen(s1)+1];
        strcpy(s2,s1);
        j=strlen(s2);
        for(int i=0;i<strlen(s2);i++)
        {
            x.push(s2[i]);
        }
        while(!x.empty())
        {
            while((!x.empty()&&!y.empty())&&((x.top()=='('&&y.top()==')')||(x.top()=='['&&y.top()==']')))
            {
                x.pop();y.pop();
            }
            if(!x.empty())
            {
                y.push(x.top());
                x.pop();
            }
        }
        if(x.empty()&&y.empty())
        {
            cout<<"Yes\n";
        }
        else
        {
            cout<<"No\n";
        }
    }
    return 0;
}

意见反馈 || 任何建议

联系我(新浪)
邮箱:qianlizhihao@gmail.com

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,811评论 0 23
  • 大孩子们都吵着要过儿童节。应了“返璞归真”这一成语。 小时候想着快点长大,偷穿着妈妈的高跟鞋,嘴里不忘叼着一根从爸...
    帽檐口袋阅读 295评论 0 0
  • 今天的一则新闻,一个美丽的准新娘工作猝死。 在看见这则新闻之前,我还在刷各种微信公众号推荐的文章,什么不努力的女人...
    苏叙阅读 427评论 0 7
  • 在炎热的七月,热得不想出门,不想上街,只想把自己关在空调房里……但我在走廊里遇见了她,一个很特别的女子。...
    舒坦一生阅读 316评论 0 2
  • 《减肥能喝咖啡吗?》 这个问题我在服务顾客的过程遇到无数次, 作为每一个咖啡控,你们的答案是什么呢,今天我们一起来...
    佩佩_3d0c阅读 311评论 0 1