我必须在java中使用转义字符(Q)进行RLE算法
示例1如果我有如下输入:
77777 => 57
BBBBBBBBB => 10B
FBFB8923 => 004FBFB8923
2365553422 => 005236555342200
这是我做的代码:
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;
}
问题在于数字如thisaaabbcccc666iii =&gt; aaabbcccc6633333ii
答案 0 :(得分:0)
尝试,
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();
}
如果输入为aaabbcccc666iii
,则将其压缩为3a2b4c363i
String example = "aaabbcccc666iii";
System.out.println(encode(example));
输出
3a2b4c363i