• 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 }
  • 相关阅读:
    祖传屎山代码
    WebService原理及重要术语
    ML-For-Beginners
    Row Level Security行级数据安全,简称RLS。
    浅析 Dapr 里的云计算设计模式
    讲师征集| .NET Conf China 2021正式启动
    为什么 Dapr 如此令人兴奋
    Open Application Model(OAM)的 Kubernetes 标准实现 Crossplane 项目 成为 CNCF 孵化项目
    kubectl 的插件管理工具krew
    PrimeBlazor 组件以MIT 协议开源
  • 原文地址:https://www.cnblogs.com/SBSOI/p/5574980.html
Copyright © 2020-2023  润新知