hdu 1020 Encoding

本文介绍了一种简单的字符串压缩算法,并提供了Java与C语言的实现代码。该算法将连续重复的字符替换为字符及其出现次数,忽略只出现一次的字符。文章通过示例详细解释了算法的工作原理。

Time Limit:1000MS     Memory Limit:32768KB     64bit IO Format:%I64d & %I64u

 

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
 
 
AC Code --Java
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		while (n-- != 0) {
			String a = sc.next();
			char[] arr = a.toCharArray();

			char[] zc = new char[10000];
			int[] zs = new int[5000];
			int j = 0;
			zc[0] = arr[0];
			for (int i = 1; i < arr.length; i++) {
				if (arr[i] == arr[i - 1]) {
					zs[j]++;
				} else {
					zc[++j] = arr[i];
				}
			}

			for (int i = 0; i < j + 1; i++) {
				if (zs[i] == 0)
					System.out.print(zc[i]);
				else
					System.out.print(zs[i] + 1 + "" + zc[i]);
			}
			System.out.println();
		}
	}
}

 C 代码版

#include <stdio.h>

void out(char arr[100]);
int main(void)
{

    int n=0,i=0;
    char arr1[100][100];
    while(scanf("%d",&n)!=EOF)
    {
        getchar();
        for(i=0;i<n;i++)
        {
            gets(arr1[i]);
        }

        for(i=0;i<n;i++)
        {
            out(arr1[i]);
        }
    }

    return 0;
}
void out(char arr[100])
{
    char s[100];
    int sum[100];
    int i=0,j=0;
    s[0]=arr[0];
    sum[0]=1;
    for(i=1;i<strlen(arr)+1;i++)
    {
        if(arr[i]==arr[i-1])
            sum[j]++;
        else
        {
            s[++j]=arr[i];
            sum[j]=1;
        }
    }
    s[j]='\0';
    for(i=0;i<strlen(s);i++)
        if(sum[i]!=1)
            printf("%d%c",sum[i],s[i]);
        else
            printf("%c",s[i]);
    printf("\n");
}

  

 

转载于:https://www.cnblogs.com/A--Q/p/5588838.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值