小Q想要给他的朋友发送一个神秘字符串,但是他发现字符串的过于长了,于是小Q发明了一种压缩算法对字符串中重复的部分进行了压缩
对于字符串中连续的m个相同字符串S将会压缩为 [m|S] (m为一个整数且1<=m<=100),例如字符串ABCABCABC将会被压缩为[3|ABC],现在小Q的同学收到了小Q发送过来的字符串,你能帮助他进行解压缩么?
输入第一行包含一个字符串s,代表压缩后的字符串。
S的长度<=1000;
S仅包含大写字母、[、]、|;
解压后的字符串长度不超过100000;
压缩递归层数不超过10层;
输出一个字符串,代表解压后的字符串。
HG[3|B[2|CA]]F
HGBCACABCACABCACAF
由内向外替换,r 代表从左侧第一个开始的 ‘]‘ 的位置, l 代表与当前 ‘]‘ 对应的 ‘[‘ 位置。
k 记录生成次数。每轮替换完 l 回到 r 的位置开始新一轮替换。
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cin >> str;
for (int r = 0; r < str.length(); r++)
{
if (str[r] == ']')
{
int k = 0;
int l = r;
for (; str[l] != '['; l--)
if (str[l] == '|')
k = l;
int num = stoi(str.substr(l + 1, k- l));
string s1 = str.substr(k + 1, r - k - 1);
string s2;
for (int i = 0; i < num; i++)
s2 += s1;
str = str.replace(l, r - l + 1, s2);
r = l;
}
}
cout << str;
}
原文:https://www.cnblogs.com/eisuto/p/12464469.html