【FOJ 1360】 Run Length Encoding

题目描述

Problem 1360 Run Length Encoding

解题思路

将一个字符串压缩表示。重复次数大于9次的要分开算,没有重复的连续序列开头和结尾要各输出个1,序列中的1要输出两个1。
AAAAAABCCCC 表示为 6A1B14C
12344 表示为 11123124
可以先不考虑题目的特殊压缩要求,先转换成普通压缩,再进行细节上的操作。

参考代码

#include <cstdio>
#include <iostream>
#include <string>
void print(char c);
using namespace std;
int main()
{
    string str;
    while (getline(cin,str)){
        string temp;
        int i = 0,cnt = 1;
        //转换成普通压缩
        while(str[i] != '\0'){
            if(str[i+1] == str[i])
                cnt++;
            else{
                while (cnt > 9){//大于9次做处理   
                        temp.push_back('9'); 
                        temp.push_back(str[i]);                         
                        cnt -= 9;
                    }
                temp.push_back(cnt+'0');
                temp.push_back(str[i]);
                cnt = 1;
            }
            i++;
        }
        //压缩完存在temp中
        int len = temp.length();
        bool first = true;
        for (i = 0;i < len;){
            if (temp[i] == '1'){//单个字符
                while (temp[i] == '1'){
                    if (first){//看是不是序列的头
                        printf("1");//则要在前面多输出个“1”
                        print(temp[i+1]);
                        first = false;
                    }else
                        print(temp[i+1]);//序列的中间部分
                    if (temp[i+2] != '1'){//如果为序列的尾部
                        printf("1");//也输出个“1”
                        first = true;
                    }
                    i += 2;     
                }
            }else{//如果不是单个字符的话,不做特殊处理
                printf("%c%c",temp[i],temp[i+1]);
                i += 2;
            }   
        }
        printf("\n");
    }
    return 0;
}
void print(char c){
    (c == '1')?printf("11"):printf("%c",c);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值