压缩算法_腾讯笔试

小Q想要给他的朋友发送一个神秘字符串,但是他发现字符串的过于长了,于是小Q发明了一种压缩算法对字符串中重复的部分进行了压缩,对于字符串中连续的m个相同字符串S将会压缩为m|S,例如字符串ABCABCABC将会被压缩为[3|ABC],现在小Q的同学收到了小Q发送过来的字符串,你能帮助他进行解压缩么?

输入描述:
输入第一行包含一个字符串s,代表压缩后的字符串。
S的长度<=1000;
S仅包含大写字母、[、]、|;
解压后的字符串长度不超过100000;
压缩递归层数不超过10层;

输出描述:
输出一个字符串,代表解压后的字符串。
示例1
输入
HG[3|B[2|CA]]F
输出
HGBCACABCACABCACAF
说明
HG[3|B[2|CA]]F−>HG[3|BCACA]F−>HGBCACABCACABCACAF

思路: 得熟悉string库函数

  1. old.substr(pos, len) 从old字符串pos位置开始截取len长度
  2. old.replace(old.pos, old.len, new_string) 从old字符串pos位置开始, len长度字符串用new_string代替, 不需同等长度字符串
  3. stoi(string_of_nums) 将string_of_nums字符串代表的数字用转为int类型.
#include<iostream>
#include<string>
using namespace std;
 
int main() {
    ios::sync_with_stdio(false);
    string str;
 
    cin >> str;
    int i, k, j = 0;
    while (j < str.length()) {
        if (str[j] == ']')
        {
            i = j;
            while (str[i] != '[')
            {
                if (str[i] == '|')
                    k = i;
                i--;
            }
            string num1 = str.substr(i + 1, k - i - 1);
            int num = stoi(num1);
            string temp = str.substr(k + 1, j - k - 1);
            string s;
            for (int i = 0; i < num; i++)
                s += temp;
 
            str.replace(i, j - i + 1, s);
            j = i;
        }
        j++;
    }
    cout << str;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值