[编程题]压缩算法
时间限制:C/C++ 2秒,其他语言4秒
空间限制:C/C++ 256M,其他语言512M
小Q想要给他的朋友发送一个神秘字符串,但是他发现字符串的过于长了,于是小Q发明了一种压缩算法对字符串中重复的部分进行了压缩,对于字符串中连续的m个相同字符串S将会压缩为[m|S](m为一个整数且1<=m<=100),例如字符串ABCABCABC将会被压缩为[3|ABC],现在小Q的同学收到了小Q发送过来的字符串,你能帮助他进行解压缩么?
输入描述:
输入第一行包含一个字符串s,代表压缩后的字符串。 S的长度<=1000; S仅包含大写字母、[、]、|; 解压后的字符串长度不超过100000; 压缩递归层数不超过10层;
输出描述:
输出一个字符串,代表解压后的字符串。
输入例子1:
HG[3|B[2|CA]]F
输出例子1:
HGBCACABCACABCACAF
例子说明1:
HG[3|B[2|CA]]F−>HG[3|BCACA]F−>HGBCACABCACABCACAF
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
string input, output;
getline(cin, input);
output = input;
int end = string::npos;
int begin = string::npos;
end = output.find(']', 0);
while(end != string::npos)
{
begin = output.rfind('[', end);
if(begin != string::npos)
{
string convertor_old = output.substr(begin, end - begin + 1);
int number_begin = convertor_old.find('[', 0) + 1;
int number_end = convertor_old.find('|', number_begin) - 1;
string convertor_number = convertor_old.substr(number_begin, number_end - number_begin + 1);
int m = atoi(convertor_number.c_str());
int letter_begin = convertor_old.find('|', 0) + 1;
int letter_end = convertor_old.find(']', letter_begin) - 1;
string convertor_letter = convertor_old.substr(letter_begin, letter_end - letter_begin + 1);
string convertor_new;
while(m--)
{
convertor_new += convertor_letter;
}
output.erase(begin, end - begin + 1);
output.insert(begin, convertor_new);
end = output.find(']', begin + convertor_new.size());
}
else
{
end = output.find(']', end);
}
}
if(output.size() > 100000)
{
output.erase(100000, output.size() - 100000);
}
cout << output.c_str() << endl;
}