题解 P1928 【外星密码】

· · 题解

这题的关键问题在于有多重的压缩嵌套。对此,有两种的解决方案。

  1. 遇到一层嵌套时递归进去,展开完成后回到这一层
  2. 遇到一层嵌套时堆栈,把重复次数和字符串记下来,展开时逐层出栈

这里我们来讲第2种方案:

思路讲解

首先我们要清楚,我们要存什么?

我们要记录的是要复制的字符串和复制的次数!

那么我们开个pair封装一下栈,然后开始写栈的基本操作。我们要写的基本操作有以下这些:

于是我们搞出了这些代码:

pair <int,string> z[20];   //栈
int lz=0;  //栈顶指针(栈的长度)

void pht(int a) {
    lz++;  
    z[lz].first=a;
}
 //数字入栈

void phst(string c) {
    z[lz].second+=c;
}
  //栈顶字符串拼接

int topt() {
    return z[lz].first;
}
  //数字出栈

string topst() {
    return z[lz].second;
}
  //字符串出栈

void pop() {
    z[lz].second="";  //一定要记得要设成空串
    lz--;
}
  //删除栈顶元素

这里我认为写STL可能会太慢,所以手写栈。写STL也可以,供大家自行实现。

接下来写主函数:

想想这样一个问题:如果你读入一个字符c,问c有几种情况?

answer:4种情况。左括号,右括号,大写字母,数字字符。

分别处理:

完整AC代码

#include<iostream>
#include<cstdio>
#include<string>
using namespace std;
string ans="";
pair <int,string> z[20];
int lz=0;
void pht(int a) {
    lz++;
    z[lz].first=a;
}
void phst(string c) {
    z[lz].second+=c;
}
int topt() {
    return z[lz].first;
}
string topst() {
    return z[lz].second;
}
void pop() {
    z[lz].second="";
    lz--;
}
  //手写栈部分(上文已讲解)

int main() {
    char ch;  //存储读进来的字符
    int tnum;  //临时数字变量
    string tqz;  //临时字符串变量
    while(cin>>ch) {
        switch(ch) {
            case '[':
                while(ch=='[') {
                    cin>>ch;
                    tnum=0;  //
                    while(ch>='0'&&ch<='9') {
                        tnum=tnum*10+(ch-'0');
                        cin>>ch;
                    }
                    pht(tnum);  //压入数字
                }
                tqz=ch;  //把char改成string
                phst(tqz);  //拼入栈顶字符串
                break;

            case ']':
                tqz="";  //记得每次调用临时字符变量时要清空
                tnum=topt();  //取出栈顶数字
                for(int i=0; i<tnum; i++)
                    tqz+=topst();  //复制栈顶字符串
                pop();  //删除栈顶元素
                if(!lz)   //判断栈是否为空并执行对应操作
                    ans+=tqz;
                else
                    phst(tqz);
                break;

            default :
                if(!lz) ans+=ch;
                else {
                    tqz=ch;
                    phst(tqz);
                }

        }
    }
    cout<<ans<<endl;   //要加上换行才能AC哦
    return 0;
}