题目可以在牛客网腾讯2020技术综合查到 第一题
string compress(string str) {
// write code here
if(str.size() == 0) return str;
int i=0;
while(i < str.size())
{
if(str[i] == ']')
{
int j = i; // i为]的位置,j 为[的位置
string res; // 用来存储每次解密后的字符串
while(str[j] != '[')
{
j--;
}
string temp = str.substr(j+1, i-j-1);
int repeat = stoi(temp.substr(0, temp.find('|')));
string repeatStr = temp.substr(temp.find('|')+1, temp.size() - temp.find('|'));
for(int i = 0; i < repeat; i++)
{
res += repeatStr;
}
str.replace(j, i - j + 1, res);
i = j;
}
++i;
}
return str;
}
本文详细解析了如何使用C++实现字符串压缩算法,通过实例展示了如何处理括号序列并重复替换子串,提升字符串效率。重点在于理解字符匹配和替换的过程,适用于面试和技术挑战问题解决。

1063





