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 }
  • 相关阅读:
    js字符串数组['1','2','3']转number
    antd-vue中给table表格整行加点击事件
    vue中路由在新的标签页打开
    antd中的form表单 initialValue导致数据不更新问题
    vue中computed的作用以及用法
    gitlab新增ssh
    CentOS7安装配置ActiveMQ
    利用已有的缓存地图文件发布ArcGIS Server瓦片服务
    CentOS7上使用源码安装物联网大数据平台TDengine
    一些可以使用的在线地图服务
  • 原文地址:https://www.cnblogs.com/fenhong/p/4667617.html
Copyright © 2011-2022 走看看