public static String decompressString (String text) {
int count = 0;
StringBuilder result = new StringBuilder () ;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (Character.isDigit(c)) {
count = count * 10 + c - '0';
} else {
while (count >0){
result.append(c);
count--;
}
}
}
return result.toString();
}
该程序应该从主方法(例如 5A5Bcd)获取游程长度编码字符串,并以游程长度解码格式返回该字符串。 5A5Bcd -> AAAAABBBBBcd。我遇到的问题是代码似乎忽略了前面没有数字的字符。在上面的示例中,我返回 AAAAABBBBB 而不是 AAAAABBBBBcd; “c”和“d”前面没有数字,因此无法识别。任何想法,我已经被困在这一点上很长一段时间了。
最佳答案
当您在示例中遇到“c”和“d”字符时,您的 count
变量不会为非零,因为在处理“5B”后它会递减为零。
我在代码中看到的最简单的修复方法是在 while
循环之前添加检查:
if (Character.isDigit(c)) {
// ...
} else {
if (count == 0) {
// Single-run-length characters have an implicit "1" prepended
count = 1;
}
while (count > 0) {
// ..
}
}
关于Java 游程长度解码(扩展压缩字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49101408/