题目描述
对于字符串中连续的M个相同字符串S将会压缩为[M|S](M为一个整数且1<=M<=100),例如字符串ABCABCABC将会压缩为[3|ABC],现在接收一段字符串,对其进行解压缩。
输入描述:
输入第一行包含一个字符串s,代表压缩后的字符串。
s的长度<=1000;
s仅包含大写字母、[、|、];
解压后的字符串长度不超过100000;
输出描述
输出一个字符串,代表解压后的字符串。
示例:输入HG[3|B[2|CA]]F
输出HGBCACABCACABCACAF
解题思路:
从右往左搜索,记录右中括号次数,查找与右括号次数相同的左括号为一个大的重复。使用堆栈进行操作,数组进行保存。
代码
#include "stdafx.h"
#include <iostream>
#include <string>
#include<stack>
#include<vector>
using namespace std;
int main()
{
string temp;
cin>>temp;
stack<char> save;
for (int i = 0; i < temp.size(); i++)
{
save.push(temp[i]);
}
vector<char> result;
vector<vector<char>> save_result;
while (!save.empty())
{
int count = 0;
if (save.top()>='A' && save.top()<='Z')
{
result.insert(result.begin(), save.top());
save.pop();
}
else if (save.top() == ']')
{
count++;
save.pop();
}
while (count)
{
int no = 0, cnt = 0;
if (save.top() == '|')
{
save.pop();
while (save.top() >= '0'&& save.top() <= '9')
{
char s1 = save.top();
no += pow(10, cnt)*(int)(s1-'0');
cnt++;
save.pop();
}
int size = result.size();
no--;
while (no)
{
for (int i = 0; i < size; i++) result.push_back(result[i]);
no--;
}
no = 0, cnt = 0;
}
else if (save.top() == ']')
{
count++;
save.pop();
}
else if (save.top() == '[')
{
count--;
save.pop();
}
else
{
result.insert(result.begin(),save.top());
save.pop();
}
}
save_result.insert(save_result.begin(),result);
result.clear();
}
for (int i = 0; i < save_result.size(); i++)
{
for (int j = 0; j < save_result[i].size(); j++) cout << save_result[i][j];
}
return 0;
}