您的位置:首页 > 其它

HDU 1020-Encoding

2018-01-24 22:34 411 查看


Encoding

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 50393    Accepted Submission(s): 22454


Problem Description

Given a string containing only 'A' - 'Z', we could encode it using the following method: 

1. Each sub-string containing k same characters should be encoded to "kX" where "X" is the only character in this sub-string.

2. If the length of the sub-string is 1, '1' should be ignored.

 

Input

The first line contains an integer N (1 <= N <= 100) which indicates the number of test cases. The next N lines contain N strings. Each string consists of only 'A' - 'Z' and the length is less than 10000.

 

Output

For each test case, output the encoded string in a line.

 

Sample Input

2
ABC
ABBCCC

 

Sample Output

ABC
A2B3C

题意:

本题的题意若理解对了就好说,开始第一遍就过了一遍题目,以为在给定的字符串的里面统计相同字母的个数,但其实并没有那么麻烦。

本题是给定你一个字符串,最大长度为10000,让你将该字符串编码,编码的方式是如果有一个子串中的字母都是相同的,即K个X,则编码为KX,如果该K为1,则省略1

分析:

我们只需要比较相邻字母是否相同,也就是说统计连续相同的字母的个数,因为题中说有K个X是给定字符串的子串。

#include <iostream>
#include<stdio.h>
#include<math.h>
#include<cstring>
#include<string.h>
#include<map>
using namespace std;

int main()
{
int n,m,len;
char s[10005];
scanf("%d",&m);
getchar();
for(int i=0;i<m;i++)
{
n=1;//初始为1,便于统计
scanf("%s",s);
len=strlen(s);
for(int j=0;j<len-1;j++)
{
if(s[j]==s[j+1])
n++;
else if(s[j]!=s[j+1]&&n>1)
{
printf("%d%c",n,s[j]);
n=1;//如下一个不和上一个相同,输出结果的同时也要将n恢复为1
}
else//如果n是1,则不需要输出n的值
{
printf("%c",s[j]);
}
}
if(s[len-1]!=s[len-2])//如果最后一个字母和倒数第二个字母不相同的话,就直接输出最后一个字母,换行
printf("%c\n",s[len-1]);
else if((s[len-1]==s[len-2]))//如果最后一个字母和倒数第二个字母相等,则连同数字一块输出,换行
printf("%d%c\n",n,s[len-1]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: