Run Length Encoding
Source : University of Ulm Internal Contest 2004 | |||
Time limit : 1 sec | Memory limit : 32 M |
Submitted : 297, Accepted : 77
Your task is to write a program that performs a simple form of run-length encoding, as described by the rules below.
Any sequence of between 2 to 9 identical characters is encoded by two characters. The first character is the length of the sequence, represented by one of the characters 2
through 9
. The second character is the value of the repeated character. A sequence of more than 9 identical characters is dealt with by first encoding 9 characters, then the remaining ones.
Any sequence of characters that does not contain consecutive repetitions of any characters is represented by a 1
character followed by the sequence of characters, terminated with another 1
. If a 1
appears as part of the sequence, it is escaped with a 1
, thus two 1
characters are output.
Input
The input consists of letters (both upper- and lower-case), digits, spaces, and punctuation. Every line is terminated with a newline character and no other characters appear in the input.
Output
Each line in the input is encoded separately as described above. The newline at the end of each line is not encoded, but is passed directly to the output.
Sample Input
AAAAAABCCCC 12344Sample Output
6A1B14C 11123124
这道题困难的地方在题目意思。。。贡献了几次WA之后才搞懂。就是多个字符出现时,用出现次数+该字符表示,多个连续的单个字符出现时,直接输出,并在其前后各输出一个1,如果其中有字符1,则用两个1代替。对于次数多余9个的,先输出 9+该字符,再按照之前的规则处理后续字符。
大致思路:先记录并统计每个字符出现的次数,然后开始输出。代码如下:
#include <iostream>
#include <queue>
#include <string>
using namespace std;
int main()
{
int i,flag,cnt;
queue <char> code;
queue <int> num;
string input;
char c;
while(getline(cin, input))
{
if(input.length()==0)//回车直接输出
{
cout<<endl;
continue;
}
while(!code.empty())
code.pop();
while(!num.empty())
num.pop();
i=1;
cnt=1;
code.push(input[0]);
c = input[0];
while(i<input.length())//先统计各个字符的数目
{
if(cnt >= 9)//长度>=9直接输出
{
num.push(cnt);
code.push(input[i]);
c = input[i];
cnt=1;
i++;
continue;
}
if(c == input[i])
{
cnt++;
}
else
{
num.push(cnt);
cnt=1;
code.push(input[i]);
c = input[i];
}
i++;
}
num.push(cnt);
flag=0;//表示开始
while(!code.empty())
{
cnt = num.front();
num.pop();
c = code.front();
code.pop();
if(cnt != 1)
{
if(flag==1)//多个单个字符结束
cout<<"1";
cout<<cnt<<c;
flag=0;
}
else
{
if(flag==0)
{
cout<<"1";
if(c == '1')
cout<<"11";
else
cout<<c;
flag=1;
}
else
{
if(c == '1')
cout<<"11";
else
cout<<c;
}
}
}
if(flag==1)
cout<<"1";
cout<<endl;
}
return 0;
}