题目:小Q想要给他的朋友发送一个神秘字符串,但是他发现字符串的过于长了,于是小Q发明了一种压缩算法对字符串中重复的部分进行了压缩,对于字符串中连续的m个相同字符串S将会压缩为[m|S](m为一个整数且1<=m<=100),例如字符串ABCABCABC将会被压缩为[3|ABC],现在小Q的同学收到了小Q发送过来的字符串,你能帮助他进行解压缩么?
思路:利用栈来判断属于两个中括号之间的内容,处理之后再入栈,直到遍历结束。
#include<iostream>
#include<string>
#include<stack>
#include<algorithm>
using namespace std;
void treatStack(stack<char>& help){
string temp = "";
while (help.top() != '['){
char s_top = help.top();
temp += s_top;
help.pop();
}
help.pop();
reverse(temp.begin(), temp.end());
int num = 0;
int index = 0;
while (temp[index] != '|'){
num = num * 10 + (temp[index] - '0');
index++;
}
if (num != 0){
for (int i = 0; i < num; i++){
for (int j = index+1; j < temp.size(); j++){
help.push(temp[j]);
}
}
}
}
int main(){
string str;
cin >> str;
if (str.empty()){
cout << "" << endl;
return 0;
}
stack<char> help;
for (int i = 0; i < str.size(); i++){
if (str[i] == ']'){
treatStack(help);
}
else{
help.push(str[i]);
}
}
string res = "";
while (help.empty() == false){
res += help.top();
help.pop();
}
reverse(res.begin(), res.end());
cout << res << endl;
system("pause");
return 0;
}