Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

rle compression algorithm java

I have to do a RLE algorithm in java with the escape character (Q)

Example 1 if i have an input like:

77777 => 57
BBBBBBBBB => 10B
FBFB8923 => 004FBFB8923
2365553422 => 005236555342200

this is the code that i made:

public String coderRLE(string text) {
            String res = new String();
            char[] charArray = text.toCharArray();
            char caractere = 0;
            int num = 0;
            int i = 0;
            for (char c : charArray) {
                if (c != caractere && i != 0) {
                    if (num >= 2) {
                        res += num;
                        res += caractere;
                    } else {
                        res += caractere;
                    }
                    num = 1;
                } else {
                    num++;
                }
                caractere = c;
                i++;
            }
            if (num >= 2) {
                res += num;
                res += caractere;
            } else {
                res += caractere;
            }
            return res;
    }

public String decoderRLE(String text) {
            String res = new String();
            char[] charArray = text.toCharArray();
            for (int i = 0;i<charArray.length-1;i++) {
                char s = charArray[i];
                if (!Character.isDigit(s)) {
                    res += s;
                } else {
                    int num = Integer.parseInt(String.valueOf(s));
                    for (int j = 0; j < num - 1; j++) {
                        res += charArray[i+1];
                    }
                }
            }
            return res;
        }

the problem is with number like thisaaabbcccc666iii => aaabbcccc6633333ii

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try,

public static String encode(String source) {
    StringBuffer dest = new StringBuffer();
    for (int i = 0; i < source.length(); i++) {
        int runLength = 1;
        while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
            runLength++;
            i++;
        }
        dest.append(runLength);
        dest.append(source.charAt(i));
    }
    return dest.toString();
}

if the input is aaabbcccc666iii it compress it as 3a2b4c363i

String example = "aaabbcccc666iii";
System.out.println(encode(example));

Output

3a2b4c363i

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...