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

    题目:

    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, () and [] 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)
    如果它是空字符串
    (b)
    如果A和B是正确的,AB是正确的,
    (c)
    如果是A正确的,(A)和[A]是正确的。
    思路:

       先输入一个数组并且创建一个栈,后遍历数组中的字符,如果是'('或'['时就入栈,如果等于栈顶就将栈顶的字符删除;

    最后判断栈是否为空,为空输出Yes,否则为No。

    注意当数组为/n是输出Yes。

    相关知识:

    栈提供了如下的操作

    1. s.empty()               如果栈为空返回true,否则返回false  
    2. s.size()                返回栈中元素的个数  
    3. s.pop()                 删除栈顶元素但不返回其值  
    4. s.top()                 返回栈顶的元素,但不删除该元素  
    5. s.push()                在栈顶压入新元素  
     1 #include<iostream>
     2 #include<stack>
     3 #include<cstdio>
     4 #include<cstring>
     5 using namespace std;
     6 int main()
     7 {
     8 int t,i;
     9 char b[150];
    10 cin>>t;
    11 getchar();
    12 while(t--)
    13 {
    14 stack<char>a;
    15 gets(b);
    16 if(strcmp(b,"/n")==0)
    17 {cout<<"Yes"<<endl;
    18 continue;
    19 }
    20 for(i=0;b[i];)
    21 {if(a.empty())
    22      a.push(b[i]);
    23  else   if((a.top()=='('&&b[i]==')')||(a.top()=='['&&b[i]==']'))
    24           a.pop();
    25             else  
    26                 if(b[i]=='('||b[i]=='[')
    27                     a.push(b[i]);
    28                 i++;
    29 }               
    30 if(a.empty())
    31 cout<<"Yes"<<endl;
    32 else  cout<<"No"<<endl;
    33 }
    34 return 0;
    35 }
  • 相关阅读:
    UVA12125 March of the Penguins (最大流+拆点)
    UVA 1317 Concert Hall Scheduling(最小费用最大流)
    UVA10249 The Grand Dinner(最大流)
    UVA1349 Optimal Bus Route Design(KM最佳完美匹配)
    UVA1212 Duopoly(最大流最小割)
    UVA1395 Slim Span(kruskal)
    UVA1045 The Great Wall Game(二分图最佳匹配)
    UVA12168 Cat vs. Dog( 二分图最大独立集)
    hdu3488Tour(KM最佳完美匹配)
    UVA1345 Jamie's Contact Groups(最大流+二分)
  • 原文地址:https://www.cnblogs.com/fenhong/p/4667617.html
Copyright © 2011-2022 走看看