面试记录————简单的字符串压缩实现

    @Test
    public void zipString() {
        String data="AAABBBaaaeeefssaaffss";
        char[] dst = new char[data.length()];
        data.getChars(0,data.length(),dst,0);
        List<ByteInfo> infos = new ArrayList();
        int j = 1;
        for(int i = 0;i<dst.length;i += j ) {
            j = 1;
            ByteInfo info = new ByteInfo();
            char current = dst[i];
            info.b = current;
            info.count = 1;
            info.pos = i;
            for(int jj = i+1;jj<dst.length;jj++) {
                if(current == dst[jj]) {
                    info.count = info.count+1;
                    j = j+1;
                }else {
                    break;
                }
            }
            infos.add(info);
        }
        StringBuilder builder = new StringBuilder();
        for(ByteInfo info : infos){
            if(info.count>1){
                builder.append(info.b).append(info.count);
            }else{
                builder.append(info.b);
            }
        }
        System.out.println(builder.toString());
    }

    class ByteInfo {
        char b;
        int count;
        int pos;
    }

输出结果如下:A3B3a3e3fs2a2f2s2

    原文作者:过自己想过的生活
    原文地址: https://blog.csdn.net/u011043551/article/details/80660288
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞