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
。有没有人看到我可能会遗漏一些东西,因为它要排除那部分字符串?
答案 0 :(得分:2)
您永远不会在循环的最后一次运行中将const epubMetadata = require('epub-metadata');
epubMetadata.getInfo('path/to/file').then(function(data) {
console.log(data);
});
添加到currentChar
。
对于性能,我强烈建议您在newString
中构建结果,而不是附加到StringBuilder
。附加到String
总是会创建一个新的String-Object,这会花费时间并导致大量对象创建。