杭电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:
-
Each sub-string containing k same characters should be encoded to “kX” where “X” is the only character in this sub-string.
-
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。现对这些字符串按一定的规则处理:
- 如果存在k个相同字符“X”的子字符串,则把这个子字符串用“kX”来表示。
- 如果k=1,则省略“k”。
解题思路
本题的思路其实很简单,循环、统计、写入新的字符数组,但是我尝试了没多次都没有“AC”,后来我才意识到了几个问题,在这里说一下,如果你还没“AC”,希望能帮到你。
- 我一开始想用string来接收每一个测试用例,后来才发现,string对象根本无法容纳10000个字符,所以要用字符数组来接收测试用例。
- 在统计相同字符的长度时,要注意其长度是有可能大于等于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平台运行检查,如发现错误,欢迎指出和纠正,谢谢!