ZOJ Problem Set - 2478 Encoding

本文介绍了一种简单的字符串压缩编码算法,该算法通过识别并压缩连续重复的字符来减少字符串的长度。文章提供了两种实现方法,一种使用了错误的方法(通过排序和映射),另一种则是正确的实现方式。正确的方法通过遍历字符串并计数重复字符的数量来进行压缩。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 100.


Output

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


Sample Input

2
ABC
ABBCCC


Sample Output

ABC
A2B3C

 

这题一开始我理解错了意思,以为是把所有的字母从小到大排好序来算的,用map错了

#include<iostream>
#include<string>
#include<cstdio>
#include<algorithm>
#include<map>
using namespace std;
int main()
{
	ios::sync_with_stdio(false);
	int T;
	cin >> T;
	while (T--) {
		string s;
		s.clear();
		cin >> s;
		map<char, int>mp;
		mp.clear();
		for (int i = 0;s[i];i++) {
			mp[s[i]]++;
		}
		map<char, int>::iterator it;
		for (it = mp.begin();it != mp.end();++it) {
			if (it->second == 1)cout << it->first;
			else cout << it->second << it->first;
		}
		cout << endl;
	}
	return 0;
}

 

 

AC代码

#include<cstring>
#include<algorithm>
#include<cstdio>
#include<iostream>
using namespace std;
char s[10005];
int main()
{
	int T;
	cin>>T;
	while (T--) {
		int flag = 1;
		cin>>s;
		int len = strlen(s);
		for (int i = 0;i<len;i++)
		{
			if (s[i] == s[i + 1])
				flag++;
			else {
				if (flag>1)
					cout<<flag;
				cout<<s[i];
				flag = 1;
			}

		}
		cout << endl;;
	}

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值