• 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 }
  • 相关阅读:
    ASP.NET获取客户端IP地址Marc地址
    WPF(MultiBinding 数据对比验证,启用提交)
    WPF(Binding of ObjectDataProvider)
    WPF(附加属性 Slider)
    WPF(Binding of ItemsControl)
    WPF( 数据验证)
    WPF(依赖属性)
    WPF(附加属性)
    WPF(Binding of RelativeSource)
    WPF(Binding of LinQ)
  • 原文地址:https://www.cnblogs.com/SBSOI/p/5574980.html
Copyright © 2020-2023  润新知