Parentheses Balance(stack)

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. Yourprogram can assume that the maximum string length is 128.InputThe file contains a positive integer n and a sequence of n strings of parentheses ‘()’ and ‘[]’, one stringa line.OutputA sequence of ‘Yes’ or ‘No’ on the output file.

Sample Input

3

([])

(([()])))

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

Output

Yes

No

Yes

题意:判断括号是否匹配

思路:栈的应用

AC代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
using namespace std;

bool judge(char c1,char c2)
{
    if(c1=='('&&c2==')')return 1;
    if(c1=='['&&c2==']')return 1;
    return 0;
}
int main()
{
    int T;
    char str[150];
    cin>>T;getchar();
    while(T--){
        stack<char> s;
        gets(str);
        int leap=1,flag=0,cntl=0,cntr=0;
        int len = strlen(str);
        //如果为空串,返回Yes
        if(len==0){cout<<"Yes"<<endl;continue;}
        //如果向左的括号与向右的括号数量不一致,返回No
        for(int i=0;i<len;++i){
            if(str[i]=='('||str[i]=='[')    cntl++;
            else cntr++;
            if(cntr>cntl) {flag=1;break;} //判断类似:))((
        }
        if(flag==1||cntl!=cntr){cout<<"No"<<endl;continue;}
        //将向右的括号入栈,与向左的比较
        for(int i=0;i<len;++i){
            if(str[i]=='('||str[i]=='['){
                s.push(str[i]);
            }
            else if(!s.empty()){
                if(judge(s.top(),str[i])){
                    s.pop();
                    continue;
                }
                else{
                    leap=0;
                    break;
                }
            }

        }
        if(leap)  cout<<"Yes"<<endl;
        else      cout<<"No"<<endl;
    }
    return 0;
}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhangxiaoduoduo/article/details/79979197
个人分类: STL
上一篇ACboy needs your help again!(stack和queue)
下一篇{A} + {B} (set)
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭