0
点赞
收藏
分享

微信扫一扫

腾讯后台------压缩算法

修炼之士 2022-08-11 阅读 69


 

腾讯后台------压缩算法_i++

 string类型,包含很多库函数,

#include <iostream>
#include <string>
using namespace std;

int main() {
string s;
cin >> s;
int i = 0;
while (i < s.length())
{
if (s[i] == ']')
{
int j = i;//j用来向前寻找与]相匹配的[
int k = 0;//k用来记录'|'所在位置
while (s[j] != '[')
{
if (s[j] == '|')
k = j;
j--;
}
int len = stoi(s.substr(j + 1, k - j-1));
string s1 = s.substr(k + 1, i - k - 1);
string s2;
for (int si = 0; si < len; si++)
{//将识别到的括号内容进行解码
s2 += s1;
}
s = s.replace(j, i - j + 1, s2);
i = j;//替换后i所指向的内容变化,从替换部分的头开始再寻找
}
i++;
}
cout << s << endl;
}

下面代码通过30%case,,,to_string函数一般将int转化成string型,  会将char转换成ASIIC码 “AB”   转成 "6566"

#include<iostream>
#include<stack>
#include<string>
#include<algorithm>
using namespace std;
int main()
{

string str;
while (cin >> str)
{
//cout << str << endl;
stack<string>record;
for (int i = 0; i < str.size(); i++)
{
if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= '0' && str[i] <= '9') || str[i] == '|' || str[i] == '[')
{
//cout << str[i] << endl;
string tmp;
tmp.push_back(str[i]);
record.push(tmp);
}
else if (str[i] == ']')
{
string str_1 = "";
while (record.top() != "|")
{
str_1 += record.top();
record.pop();
}
record.pop();
string str_2 = "";
while (record.top() != "[")
{
str_2 += record.top();
record.pop();
}
record.pop();
int n = atoi(str_2.c_str());
for (int i = 0; i < n; i++)
{
record.push(str_1);
}
}
}
string res="";
while (record.empty() == false)
{
//cout << record.top() << endl;
res += record.top();
record.pop();
}
//cout << res << endl;
reverse(res.begin(), res.end());
//cout << "1" << endl;
cout << res << endl;
}
}

 

举报

相关推荐

0 条评论