字符串压缩之C++实现

题目: 输入一个字符串,输出对其压缩过的形式。
    如输入为:aaabbbccc则输出为3a3b3c;如输入为abbc,则输出为a2bc。
    aaabbbccc  ---->  3a3b3c

    abc        ---->  abc


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

int main()
{
    int cnt = 1;///cnt the number of every char
    int pos = 1;
    char tmp_A,tmp_B;
    string ori_str, sht_str;
    string::size_type ori_len;
    char c_cnt;
    cout<<"input the ori string"<<endl;
    cin>>ori_str;

    ori_len = ori_str.size();
    for (; pos < static_cast<int>(ori_len); ++pos)
    {
        tmp_A = ori_str[pos - 1];
        tmp_B = ori_str[pos];



        if (tmp_A != tmp_B && pos != static_cast<int>(ori_len-1))
        ///没到末尾的时候,AB不同
        {
            if (cnt == 1)
            {
                sht_str.push_back(tmp_A);
            }
            else
            {
                c_cnt = cnt + '0';
                sht_str.push_back(c_cnt);
                sht_str.push_back(tmp_A);
                cnt = 1;
            }
        }
        else if (tmp_A != tmp_B && pos == static_cast<int>(ori_len-1))
        ///在末尾,但是A,B不同
        {
            if (cnt == 1)
            {
                sht_str.push_back(tmp_A);
            }
            else
            {
                sht_str.push_back(cnt);
                sht_str.push_back(tmp_A);
                cnt = 1;
            }
            sht_str.push_back(tmp_B);
        }
        else if (tmp_A == tmp_B && pos != static_cast<int>(ori_len-1))
        ///不在末尾,AB相同
        {
            ++cnt;
        }
        else if (tmp_A == tmp_B && pos == static_cast<int>(ori_len-1))
        ///在末尾,AB相同
        {
            cnt++;
            c_cnt = cnt + '0';
            sht_str.push_back(c_cnt);
            sht_str.push_back(tmp_A);
        }
    }

    cout<<sht_str;
    return 0;
}


  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值