zoukankan      html  css  js  c++  java
  • 平衡括号问题

    题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=83498#problem/A

    题意:

         多组案例,输入由'('、')'、'['和']'组成的括号序列,判断是否合法(构成平衡)。合法条件如下:

             1)空字符串合法。

             2)如果A和B都合法,则AB合法。

             3)如果A合法则(A)和[A]都合法。

           案例:

     

                  Sample Input 

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

                 Sample Output 

            Yes
            No
            Yes
    

    分析:

          括号的三种非平衡状态:1. [(]);   2. ([());   3.(()]);

          设计思想:单个括号为非平衡状态,非单括号进行以下步骤:'0’入栈,1)凡出现左括号,则进栈;2)凡出现右括号,首先检查桟顶元素是否匹配,若匹配则栈顶元素出桟,否则'1'入栈,结束判断;3)表达式检验结束时,若桟顶元素为'0',则匹配正确即括号平衡,否则匹配失败即括号不平衡。

    源代码:

     1 #include<cstdio>
     2 #include<cstring>
     3 #include<stack>//桟的头文件声明
     4 using namespace std;
     5 const int maxn=130;
     6 char str[maxn];
     7 stack<char> s;//建立一个桟s
     8 int main()
     9 {
    10     int n,len;
    11     scanf("%d",&n);//案例数
    12     getchar();
    13     while(n--)
    14     {  
    15         gets(str);//输入字符串
    16         len=strlen(str);//字符串长度
    17         if(len==1)//单个括号不构成平衡
    18           puts("No");
    19         else
    20         {  
    21             s.push('0'); //判定平衡依据
    22            for(int i=0;i<len;i++)
    23            {   if(str[i]=='('||str[i]=='[')//左括号入栈
    24                  s.push(str[i]);
    25                else if(str[i]==')')//右括号形式1
    26                {
    27                    if(s.top()=='(')//平衡括号出桟
    28                        s.pop();
    29                    else 
    30                    { 
    31                        s.push('1');//不平衡结束条件
    32                       break;
    33                    }
    34                }
    35                else  if(str[i]==']')//右括号形式2
    36                {
    37                    if(s.top()=='[')//平衡括号出桟
    38                        s.pop();
    39                    else 
    40                    {  
    41                        s.push('1');//不平衡结束条件
    42                       break;
    43                    }
    44                }
    45            }
    46            puts(s.top()=='0'?"Yes":"No");//判定平衡
    47         }
    48     }
    49         return 0;
    50 }
  • 相关阅读:
    9.4
    9.3
    9.2
    2016.9.1
    html,body
    prototype
    京东笔试题的一些小细节
    gulp安装过程中的问题。
    json
    双飞翼布局和圣杯布局
  • 原文地址:https://www.cnblogs.com/huaszjh/p/4674678.html
Copyright © 2011-2022 走看看