杭电ACM 1020 Encoding

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

问题描述与算法分析

题目的意思是当字符串存在多个相同的字符时,在每个字符前加上该字符在字符串中出现的次数。若不存在相同的字符,则只输出字符串。
基本思路:
① 构造一个字符串数组,初始化相同字符的数量num为1,把数组的第一个值str[0]赋值给临时变量temp;
② 从数组的第二个元素查找,若存在与temp值相同的字符,则执行num++,否则转向
③ 若num的值不为1,表明数组存在与str[0]相同的字符,打印出num和temp; 
若num的值为1,表明数组中str[0]对应的字符只有一个,直接打印出temp;
将num值重置为1,temp值赋值为str[i],作为下一次循环的初始条件。

代码如下

#include <iostream>
#include <string>
using namespace std;

int main()
{
	string str;
	int i,j;
	int N;
	cin>>N;
	while(N--)
	{   
		cin>>str;
		int num=1;//用于统计字符个数
		char t=str[0];//临时变量,用于判断数组是否有相同的字符
		for(i=1;i<=str.length();i++)			
		{
			if(str[i]==t)
			    num++;
			else
			{
				if(num!=1)
				{
					cout<<num<<t;
				}
				else
				{
					cout<<t;
				}
				//num和t重新赋值,作为下一次循环初始条件
				num=1;
				t=str[i];
			}
		}                     
		cout<<endl;
	}
	return 0;
}

测试结果截图



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值