• 网易2018——解码字符串


    解码字符串(C++)

    时间限制:C/C++语言1000MS;其他语言3000MS

    内存限制:C/C++语言65536KB;其他语言589824KB

    题目描述:
    给出一个表达式S,该表达式只包括数字、字母及方括号这三种元素。该表达式具有如下规则:数字只会出现在方括号前,它表示方括号内容的重复次数,方括号中的内容可以是普通的字海串,也可以另一个表达式。请写一段程序,按照上述规则格输入的表达式层开成目标字符串。

    输入:
    输入包含多组测试数据,每组数据为一行,每行数据是一个合法的高达式s,你不需要对该验入的合法性进行判断。
    输出
    输出按照上述规则展开的字符串。
    样例输入
    e3[2[abc]gh]
    e9[xyz]
    官输出
    eabcabcghabcabcghabcabcgh

    exyzxyzxyzxyzxyzxyzxyzxyzxyz

    解题思路:

      使用栈进栈出

     1 #include <iostream>
     2 #include <string>
     3 #include <vector>
     4 #include <stack>
     5 using namespace std;
     6 
     7 int main()
     8 {    
     9     vector<string>Ans;
    10     for (int n = 0; n < 2; ++n)//输入数据组数
    11     {
    12         stack<char>res;
    13         string str;
    14         cin >> str;//输入测试数组
    15         for (int i = 0; i < str.size(); ++i)
    16         {
    17             if (str[i] == ']')//栈出
    18             {
    19                 string tempstr = "";
    20                 while (res.top() != '[')
    21                 {
    22                     tempstr += res.top();//获取循环字符串
    23                     res.pop();
    24                 }
    25                 res.pop();//弹出‘[’
    26                 int i = 1, num = 0;
    27                 while (res.top() >= '0'&&res.top() <= '9')//防止是两位数字
    28                 {
    29                     num += num + (res.top()-'0')*i;
    30                     i = 10 * i;
    31                     res.pop();
    32                 }
    33                 while (num--)
    34                 {
    35                     for (int j = tempstr.size() - 1; j >= 0; --j)//循环再次入栈
    36                         res.push(tempstr[j]);
    37                 }
    38                 tempstr = "";//清空临时字符
    39             }
    40 
    41             else
    42                 res.push(str[i]);//入栈
    43         }
    44         string restr;
    45         restr.resize(res.size());
    46         int i = res.size();
    47         while (i--)
    48         {
    49             restr[i] = res.top();//反向出栈存储
    50             res.pop();
    51         }
    52         Ans.push_back(restr);    
    53     }
    54     //输出
    55     for (auto a : Ans)
    56         cout << a << endl;
    57 
    58     system("pause");
    59     return 0;
    60 }
  • 相关阅读:
    socket错误码获取
    代码整洁之道读书笔记函数
    算法学习之堆排序
    包含与继承区别
    提高 LayerBacked Memory Use
    RenderBuffer
    算法学习之快速排序
    NSTimer
    DNS and BIND ... (转载) zhumao
    Samba学习笔记(转载) zhumao
  • 原文地址:https://www.cnblogs.com/zzw1024/p/10639161.html
Copyright © 2020-2023  润新知