1078. 字符串压缩与解压 (20)

389 篇文章 1 订阅
72 篇文章 0 订阅

1078. 字符串压缩与解压 (20)
时间限制 400 ms 内存限制 65536 kB 代码长度限制 8000 B
判题程序 Standard 作者 CHEN, Yue

文本压缩有很多种方法,这里我们只考虑最简单的一种:把由相同字符组成的一个连续的片段用这个字符和片段中含有这个字符的个数来表示。例如 ccccc 就用 5c 来表示。如果字符没有重复,就原样输出。例如 aba 压缩后仍然是 aba。
解压方法就是反过来,把形如 5c 这样的表示恢复为 ccccc。
本题需要你根据压缩或解压的要求,对给定字符串进行处理。这里我们简单地假设原始字符串是完全由英文字母和空格组成的非空字符串。
输入格式:
输入第一行给出一个字符,如果是 C 就表示下面的字符串需要被压缩;如果是 D 就表示下面的字符串需要被解压。第二行给出需要被压缩或解压的不超过1000个字符的字符串,以回车结尾。题目保证字符重复个数在整型范围内,且输出文件不超过1MB。
输出格式:
根据要求压缩或解压字符串,并在一行中输出结果。
输入样例 1:
C
TTTTThhiiiis isssss a tesssst CAaaa as
输出样例 1:
5T2h4is i5s a3 te4st CA3a as
输入样例 2:
D
5T2h4is i5s a3 te4st CA3a as10Z
输出样例 2:
TTTTThhiiiis isssss a tesssst CAaaa asZZZZZZZZZZ

#define _CRT_SECURE_NO_WARNINGS
#include <algorithm>
#include <iostream>
#include <string>
#include <iomanip>

using namespace std;
const int MaxN = 110;

void AddNum(string & res, int num)
{
    string tmp;
    while (num)
    {
        tmp += num % 10 + '0';
        num /= 10;
    }
    reverse(tmp.begin(), tmp.end());
    res += tmp;
}


int main()
{
#ifdef _DEBUG
    freopen("data.txt", "r+", stdin);
#endif // _DEBUG
    std::ios::sync_with_stdio(false);

    char type;
    string str, res;
    int idx,num;
    cin >> type; cin.get();
    getline(cin, str);
    if (type == 'C')
    {
        idx = 1; num = 1;
        while (idx + 1< str.size())
        {
            if (str[idx] == str[idx - 1])++num;
            else
            {

                if (1 != num)AddNum(res, num);
                res += str[idx - 1];
                num = 1;
            }
            ++idx;
        }
        if (str[idx] == str[idx - 1])
        {
            ++num;
            AddNum(res, num);
            res += str[idx];
        }
        else
        {
            res += str[idx - 1];
            res += str[idx];
        }
    }
    else
    {
        idx = 0; num = 0;
        while (idx + 1 < str.size())
        {
            if ('0' <= str[idx] && str[idx] <= '9')num = 10 * num + str[idx] - '0';
            else
            {
                char ch = str[idx];
                if (num > 0)
                {
                    while (num)
                    {
                        res += ch;
                        --num;
                    }
                }
                else
                {
                    num = 0;
                    res += ch;
                }
            }
            ++idx;
        }
        if (num)
        {
            while (num)
            {
                res += str[idx];
                --num;
            }
        }
        else res += str[idx];
    }

    cout << res;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值