zoukankan      html  css  js  c++  java
  • UVa 673 Parentheses Balance -SilverN

    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





    用栈模拟匹配括号

     1 /*UVa 673 Parentheses Balance*/
     2 #include<iostream>
     3 #include<algorithm>
     4 #include<cmath>
     5 #include<cstring>
     6 #include<stack>
     7 using namespace std;
     8 char c[500];
     9 int n;
    10 int pd(char q,char e){//匹配 
    11     if(q=='(' && e==')')return 1;
    12     if(q=='[' && e==']')return 1;
    13     return 0;
    14 }
    15 int main(){
    16     scanf("%d
    ",&n);
    17     while(n--){
    18         gets(c);//因为可能读入空串,所以用gets 
    19         if(strcmp(c,"
    ")==0){//空串合法 
    20             printf("Yes");
    21             continue;
    22         }
    23         int flag=0;
    24         stack<char>st;
    25         int L=strlen(c);
    26         for(int i=0;i<L;i++){
    27             if(c[i]=='(' || c[i]=='[') st.push(c[i]);//左括号入栈 
    28             else{//右括号处理 
    29                 if(st.empty()){
    30                     flag=1;
    31                     break;
    32                 }
    33                 if(pd(st.top(),c[i])==1) st.pop();
    34                 else{
    35                     flag=1;
    36                     break;
    37                     }
    38             }
    39         }
    40         if(flag==1 || !st.empty())printf("No
    ");
    41         else printf("Yes
    ");
    42     }
    43     return 0;
    44 }
  • 相关阅读:
    关于json中对象的删除
    JDBC操作数据库 封装好的工具类
    json <--->List集合,实体类 之间的相互转换
    java--->>发送邮件
    登陆的过滤器
    Hadoop + Spark 在CentOS下的伪分布式部署
    CentOS和ubuntu修改hostname的区别
    ubuntu 用户管理 adduser vs useradd
    hadoop2.6.1源码编译64位
    MySQL Binlog详解
  • 原文地址:https://www.cnblogs.com/AwesomeOrion/p/5436282.html
Copyright © 2011-2022 走看看