HDU1020 Encoding

Encoding

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 36924    Accepted Submission(s): 16374


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
 
题目大意:
题目的意思就是要我们求出相同子字符串序列的个数并表示出来,题目还告诉我们,所有的字符都是 'A' - 'Z' 之间;并且如果该段连续的该字符只有一个则不需要表示出来,否则需要表示出来;
分析:
由题目所给的输入测试数据得到的输出数据  INPUT: ABBCCC   OUTPUT:A2B3C; 我们可以知道,连续段只要有相同的字符只表示出一个就好了,那么我们可以通过从后面往前面覆盖的方式来得到正确的输出字符,然后通过整型数组记录改字符在这连续段出现的次数;

覆盖相同的字符:  
例如:字符串 str =" ABBCCC  "  首先我们让 str[0]='A';  然后定义一个遍历指针,让该指针指向第二个字符,那么就有 str[1]='B';  str[2]='B';  str[3]='C'; str[4]='C'; str[5]='C'; 然后我们只需要每次都判断下前面的和后面的是否相等,如果相等的话那么就依次覆盖前面的字符:如当我们找到 str[1]==str[2] 相等时,那么我们就把从str[2]开始的字符 依次向前面覆盖,并且将字符串长度缩短 1  (len--);那么就会有 str=" ABCCC " 直到最后遍历完成,变成了 str=" ABC ";
每次找同一段相同的字符时候,我们让其对应的整型数组中的值加 1 就好了;


给出AC代码:
#include<iostream>
using namespace std;

int main()
{
	int n;
	cin >> n;
	char str[10000];
	int num[1000];
	while (n--)
	{
		memset(num, 0, sizeof(num));
		cin >> str;
		int len;
		len = strlen(str);
		for (int i = 1; i < len; i++)
		{
			if (str[i] == str[i - 1])  //如果前面的字符串和后面字符串相等则将前面的字符串覆盖。
			{
				for (int j = i; j < len; j++)
				{
					str[j - 1] = str[j];
				}
				num[i-1]++;				//每次找到相同的就加 1 ;
				len--;					//覆盖之后需要将字符串缩短;
				i--;                    //防止指针没有缘由的向前,保证指针始终指向覆盖的位置;
			}
		}
		for (int i = 0; i < len; i++)
		{
			if (num[i])cout << num[i]+1; //控制输出格式;输出的时候需把本身这个也算上,便多加个一;
			cout << str[i];
		}
		cout << endl;
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值