首页 > 基础算法 > 字符串处理 > hdu 1020 Encoding-字符串-[解题报告]
2013
11-28

hdu 1020 Encoding-字符串-[解题报告]

Encoding

问题描述 :

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.

输入:

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.

输出:

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

样例输入:

2
ABC
ABBCCC

样例输出:

ABC
A2B3C

#include <iostream>
using namespace std ;
int main()
{
    int t,i,num ;
    char a[10002];
    
    scanf("%d%*c",&t);
    while(t--)
    {
        gets(a);
        
        num=1 ;
        for(i=0;a[i]!='/0';i++)
        {
            if(a[i]==a[i+1])
            num++;
            if(a[i]!=a[i+1]||a[i+1]=='/0')
            {
                if(num==1)
                printf("%c",a[i]);
                else 
                printf("%d%c",num,a[i]);
                num=1 ;
            }
        }
        printf("/n");
    }
    return 0 ;
}

解题转自:http://blog.csdn.net/akof1314/article/details/5074221


  1. 思路二可以用一个长度为k的队列来实现,入队后判断下队尾元素的next指针是否为空,若为空,则出队指针即为所求。

  2. 第二个方法挺不错。NewHead代表新的头节点,通过递归找到最后一个节点之后,就把这个节点赋给NewHead,然后一直返回返回,中途这个值是没有变化的,一边返回一边把相应的指针方向颠倒,最后结束时返回新的头节点到主函数。