1. 程式人生 > >JAVA字串的壓縮和解壓

JAVA字串的壓縮和解壓

輸入 EEAAACCDD  壓縮成 E2A3C2D2                 

輸入 E2A3C2D2  解壓 EEAAACCDD 

程式碼:

package ss;

import java.util.Scanner;

public class Demo2 {
	public static void main(String[] args) {
		
		/*壓縮
		 * Scanner input=new Scanner(System.in);
		String  a=input.next();
		char x[]=a.toCharArray();
		StringBuffer str=new StringBuffer();
		int count=0;
		char y=x[0];
		for(char c:x){
			if(c==y){
				count++;
			}else{
				str.append(y);
				str.append(count);
				y=c;
				count=1;
			}
		}
		str.append(y);
		str.append(count);
		System.out.println(str.toString());*/
		
		
		//解壓
		Scanner input=new Scanner(System.in);
		String  a=input.next();
		char x[]=a.toCharArray();
		StringBuffer str=new StringBuffer();
		int c[]=new int[x.length/2]; 
		char m[]=new char[x.length/2]; 
		int index=0;
		int ind=0;
		for(int i=0;i<x.length;i++){
			if(i%2!=0){
				c[index]=Integer.parseInt(String.valueOf(x[i]));
				index++;
			}else{
				m[ind]=x[i];
				ind++;
			}
		}
		
		for(int j=0;j<c.length;j++){
			for(int k=0;k<c[j];k++){
			str.append(m[j]);
			}
		}
		System.out.println(str.toString());
	}
		
		
}