对输入字符串进行压缩,输入"aaabcccdde",输出"3ab3c2de",即对连续出现的字符进行压缩

public class Compress {
    public static void main(String[] args){
        String s = "aaabcccdde";
        char[] a = s.toCharArray();  //将String转化为char[]
        compress(a);
    }

    static void compress(char[] a) {
        int i = 1, j = 0;
        int count = 1;
        while(i < a.length){
            while(a[i] == a[j]){
                i++;
                count++;
            }
            if(count > 1){
                a[j+1] = (char) (count + '0');  //将int型的数字转化为char型的
                j++;
                count = 1;
            }
            a[j+1] = a[i];
            i++;
            j++;     
        }
        for(int m = 0; m < j+1; m++)
            System.out.print(a[m]);
    }
}

 

posted on 2015-03-17 00:39  lamela11  阅读(261)  评论(0)    收藏  举报

导航