java实现rle编码,rle压缩算法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

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

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值