编码问题(Encoding)

HDU 1020 Encoding

问题描述:

给定一个只包含'A'~'Z'的字符串,我们可以用如下的方法进行编码:

1、每一个包含了k个相同字符的子串,应该编码为"kX",其中X为这个子串所包含的唯一的字符;

2、如果子串的长度为1,1应该被省略。

输入:

第一行包含一个正整数$N$,$0<N≤100$,该正整数$N$表示了有$N$组测试数据;接下来的$N$行包含了$N$个字符串,每个字符串只包含ASCII 字符A~Z,且长度不超过10000。

输出:

对于每一条测试数据,输出一行编码后的字符串。

样例输入:

2

ABC

ABBCCC

样例输出:

ABC

A2B3C

这道题本身而言难度不大。整体来看,只要从头至尾扫描目标字符串,找到重复的字符,计算长度即可。计算长度时,状态的转换相对要注意一下;另外,向字符串中插入数字,我使用了sprintf函数,这样能保证大整数依然能够快速准确的插入。C++实现如下

 1 #include<iostream>
 2 #include<string>
 3 int main()
 4 {
 5     using namespace std;
 6     string input, output;
 7     char buffer[255];
 8     int n;
 9     int count;        //the total count a character appears
10     char tmpc;        //the current character
11     cin >> n;
12     for (int i = 0; i < n; i++)
13     {
14         output.clear();
15         cin >> input;
16         count = 0;
17         for (unsigned int j = 0; j < input.length(); j++)
18         {
19             if (count == 0)
20             {
21                 count++;
22                 tmpc = input[j];
23             }
24             else
25             {
26                 if (input[j] == tmpc)
27                     count++;
28                 else
29                 {
30                     if (count == 1)
31                         sprintf(buffer, "%c", tmpc);
32                     else
33                         sprintf(buffer, "%d%c", count, tmpc);
34                     output.append(buffer);
35                     count = 1;
36                     tmpc = input[j];
37                 }
38             }
39         }
40         //last string to be processed
41         if (count == 1)
42             sprintf(buffer, "%c", tmpc);
43         else
44             sprintf(buffer, "%d%c", count, tmpc);
45         output.append(buffer);
46         cout << output << endl;
47     }
48     return 0;
49 }

 

转载于:https://www.cnblogs.com/ggggg63/p/6393955.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值