【FOJ 1360】 Run Length Encoding

来源:互联网 发布:淘宝2016年营业额 编辑:程序博客网 时间:2024/05/19 13:42

题目描述

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
原创粉丝点击