题目描述
压缩算法
解法:栈(C++)
#include <bits/stdc++.h>
using namespace std;
string CompressString(string s){
stack<char> st;
for(int i=0;i<s.length();i++)
{
if(s[i]=='[') st.push(s[i]);
else if(s[i]==']')
{
char c_tmp = st.top();
string s_tmp;
while(c_tmp>='A' && c_tmp<='Z')
{
s_tmp = c_tmp + s_tmp;
st.pop();
c_tmp = st.top();
}
if(!st.empty()) st.pop();
int n = 0;
int cnt = 1;
while(st.top()>='0' && st.top()<='9')
{
n = n+(st.top()-'0')*cnt;
st.pop();
cnt *= 10;
}
string decode_string;
while(n)
{
decode_string += s_tmp;
n--;
}
if(!st.empty()) st.pop();
for(char c: decode_string)
st.push(c);
}
else st.push(s[i]);
}
string res;
while(!st.empty())
{
res = st.top() + res;
st.pop();
}
return res;
}
int main()
{
string s;
cin >> s;
string res = CompressString(s);
cout << res << endl;
return 0;
}