public static String compress(String original) {
int count = 1;
char currentChar = original.charAt(0);
String newString = "";
for (int x = 1; x < original.length(); x++) {
if (currentChar == original.charAt(x)) {
count++;
} else {
if (count == 1) {
newString += Character.toString(currentChar);
} else {
newString += Integer.toString(count) + Character.toString(currentChar);
}
count = 1;
}
currentChar = original.charAt(x);
}
return newString;
}
我上面的代码应该使用RLE对一个字符串进行编码,所以如果一个字符串
sssWWwRttty
,程序应该返回3s2WwR3ty
我遇到的问题是返回值忽略了字符串中的最后一个字符。例如,如果compress方法的参数是sssWWwRttty
返回值将是3s2WwR3t
或者如果agument是qwwwEErtttyyyyy
返回值将是q3w2Er3t
。有没有人看到我可能漏掉了什么东西,因为它排除了字符串的那一部分? 最佳答案
在循环的最后一次运行中,您从未将currentChar
添加到newString
。
为了提高性能,我强烈建议在StringBuilder
中生成结果,而不是附加到String
中附加到String
总是会创建一个新的字符串对象,这会花费时间并导致大量的对象创建。
关于java - Java程序的运行长度编码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40359555/