杭电oj HDOJ 1020 Encoding(一个简单的字符串处理)

杭电oj HDOJ 1020 Encoding

题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1020

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.

题目大意

每个测试用例都是一个全部由“A”~“Z”组成的字符数串,其长度不超过10000。现对这些字符串按一定的规则处理:

  1. 如果存在k个相同字符“X”的子字符串,则把这个子字符串用“kX”来表示。
  2. 如果k=1,则省略“k”。

解题思路

本题的思路其实很简单,循环、统计、写入新的字符数组,但是我尝试了没多次都没有“AC”,后来我才意识到了几个问题,在这里说一下,如果你还没“AC”,希望能帮到你。

  1. 我一开始想用string来接收每一个测试用例,后来才发现,string对象根本无法容纳10000个字符,所以要用字符数组来接收测试用例。
  2. 在统计相同字符的长度时,要注意其长度是有可能大于等于2位数的,不能简单地把统计出的个数直接送到新字符数组中(也就是说还要有个循环来一位一位的写)

本人的C++解决方案

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

int main()
{
	int N, i, len, j, count, pos, temp_len, k;
	char str[10000], res[10000], ch;
	string temp;
	stringstream ss;
	cin >> N;
	for (i = 0; i < N; i++) {
		cin >> str;
		len = strlen(str);
		pos = count = 0;
		for (j = 0; j < len; j++) {
			// 初始化统计字符
			if (!count) {
				ch = str[j];
				count++;
			}
			else {
				if (str[j] == ch) {
					count++;
				}
				else {
					// 如果统计长度为1,则省略1
					if (count == 1) {
						res[pos] = ch;
						pos++;
					}
					else {
						ss << count;
						ss >> temp;
						temp_len = temp.length();
						for (k = 0; k < temp_len; k++) {
							res[pos++] = temp[k];
						}
						res[pos++] = ch;
						ss.clear();
					}
					ch = str[j];
					count = 1;
				}
			}
		}
		if (count == 1) {
			res[pos++] = ch;
		}
		else {
			ss << count;
			ss >> temp;
			temp_len = temp.length();
			for (k = 0; k < temp_len; k++) {
				res[pos++] = temp[k];
			}
			res[pos++] = ch;
			ss.clear();
		}
		// 必须在最后添加“零终止符”!
		res[pos] = '\0';
		len = strlen(res);
		for (j = 0; j < len; j++) {
			cout << res[j];
		}
		cout << endl;
	}
	return 0;
}

代码通过HDOJ平台运行检查,如发现错误,欢迎指出和纠正,谢谢!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值