zoukankan      html  css  js  c++  java
  • chapter6 数据结构基础之习题 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. 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





    用栈模拟匹配括号


    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<stack>
    using namespace std;
    int compare(char p,char q)
    {
    if(p=='('&&q==')') return 1;
    if(p=='['&&q==']') return 1;
    else return 0;
    }
    int main()
    {
    int n,L,flag;
    char c[100];

    scanf("%d ",&n);
    for(int i=0; i<n; i++)
    {
    stack<char> st;
    flag=0;
    gets(c);
    L=strlen(c);
    for(int j=0; j<L; j++)
    {

    if(c[j]=='('||c[j]=='[') st.push(c[j]);
    if(c[j]==')'||c[j]==']')
    {
    if(st.empty())
    {
    flag=1;
    break;
    }
    if(compare(st.top(),c[j])) st.pop();
    else{
    flag=1;
    break;
    }
    }
    }
    if(flag==1||!st.empty()) cout<<"No"<<endl;
    else cout<<"Yes"<<endl;

    }
    return 0;
    }

  • 相关阅读:
    [转]Modernizr的介绍和使用
    java动态代理使用详解
    ajax上传文件以及使用中常见问题处理
    cmd下查询端口占用以及根据进程id名称结束进程
    水平居中 垂直居中
    inline-block和float
    一起入门前端(三)
    一起入门前端(二)
    一起入门前端(一)
    WPF初学——自定义样式
  • 原文地址:https://www.cnblogs.com/is-Tina/p/8955078.html
Copyright © 2011-2022 走看看