• Sicily 1543. Completing Brackets 解题报告


    Constraints

    Time Limit: 1 secs, Memory Limit: 32 MB

    Description

    A series of brackets is complete if we can pair off each left bracket '[' with a right bracket ']' that occurs later in the series. Every bracket must participate in exactly one such pair.

    Given a String text add the minimal number of brackets to the beginning and/or end of text to make it complete. Return the result.

    Input

    Each line of input contains a string, text. text will have between 1 and 50 characters inclusive, and contain only the characters "[" and "]". Process to the end of input.

    Output

    Output one line for each case, the result.

    Sample Input

    [[
    ][
    [[[[]]]]

    Sample Output

    [[]]
    [][]
    [[[[]]]]

     思路:

    其实是非常简单的一道题,一开始没注意看题目要求只能在开头或者结尾加上括号把问题复杂化了。

    由于这里已经给定了是'['和']'两个符号,所以连stack都不需要,直接用一个count来计数,省事!

    这里count初始化为0,当读到一个左括号时,计数器加1,读到右括号时,计时器减1,而且只要count小于0则马上加1并输出一个'[' (在左边补上数量不够的左括号),读取完后再输出count个的右括号即可。

     1 #include<iostream>
     2 using namespace std;
     3 
     4 int main(){
     5     string s;
     6     while(cin>>s){
     7         int count=0;
     8         int len=s.length();
     9         for(int i=0;i<len;i++){
    10             if(s[i]=='[')
    11                 count++;
    12             else{
    13                 count--;
    14             }
    15             if(count<0){
    16                 cout<<'[';
    17                 count++;
    18             }
    19         }
    20         cout<<s;
    21         while(count>0){
    22             cout<<']';
    23             count--;
    24         }
    25         cout<<endl;
    26     }
    27     return 0;
    28 }
  • 相关阅读:
    ASP.NET三层架构
    内网与外网IP地址
    VS中"新建网站"与"新建项目"的区别
    Div与table的区别
    JScript内存泄漏/ie内存泄漏
    CSS定位之——浮动
    OA
    padding与lineheight详解
    对WinForm的App.config文件进行加密<收藏>
    配置错误:未能使用提供程序“RsaProtectedConfigurationProvider”进行解密。提供程序返回错误信息为: 打不开 RSA 密钥容器
  • 原文地址:https://www.cnblogs.com/jolin123/p/3364436.html
Copyright © 2020-2023  润新知