题解——破译密码(递归问题)

#include <iostream>

#include <cstdio>

#include <string>

using namespace std;

string fun()    //功能单元:输入一个字符串,对它进行解密并且返回展开后的字符串

{

    char c;

    string s="",s1;

    while(scanf("%c",&c)==1)    //会对输入的字符串一个一个的读(scanf每次只能读一个,输入的字符串是放在缓冲区中的

    {

        if(c=='[')

        {

            int n;

            cin>>n;    //读入缓冲区中的一个数字

            s1=fun();       //对后面可能没有解密完全的字符串继续解密

            while(n--)  s+=s1;  //解密完后,叠加n次

        }

        else

        {

            if(c==']') return s;   //递归终止的条件

            else s+=c;          //s1的出处

        }

    }

}

int main()

{

    cout<<fun();

    return 0;

}

这篇文章,是又一个故事的结束...
lazy's story is continuing.
原文地址:https://www.cnblogs.com/Hello-world-hello-lazy/p/13522030.html