天气与日历 切换到窄版

 找回密码
 立即注册
中国膜结构网
十大进口膜材评选 十大国产膜材评选 十大膜结构设计评选 十大膜结构公司评选
查看: 2|回复: 0

字符串压缩之C++实现

[复制链接]
  • TA的每日心情
    开心
    昨天 15:23
  • 签到天数: 69 天

    [LV.6]常住居民II

    410

    主题

    167

    回帖

    2704

    积分

    管理员

    积分
    2704
    发表于 2024-6-22 09:46:18 | 显示全部楼层 |阅读模式
    题目: 输入一个字符串,输出对其压缩过的形式。
        如输入为: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;
    }

     

     

     

     

    字符串压缩之C++实现
    中国膜结构网打造全中国最好的膜结构综合平台 ,统一协调膜结构设计,膜结构施工,膜材采购,膜材定制,膜结构预算全方位服务。 中国空间膜结构协会合作单位。
    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|Archiver|手机版|中国膜结构网|中国膜结构协会|进口膜材|国产膜材|ETFE|PVDF|PTFE|设计|施工|安装|车棚|看台|污水池|

    GMT+8, 2024-7-1 05:37 , Processed in 0.056900 second(s), 22 queries .

    Powered by Discuz! X3.5

    © 2001-2024 Discuz! Team.

    快速回复 返回顶部 返回列表