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();
}程序应该从main方法(如5A5Bcd )接收一个游程长度编码的字符串,并以游程解码的格式返回该字符串。5A5Bcd -> AAAAABBBBBcd。我遇到的问题是,代码似乎忽略了前面没有数字的字符。在上面的例子中,我返回的是AAAAABBBBB而不是AAAAABBBBBcd;'c‘和'd’前面没有数字,因此无法识别。任何想法,我已经被困在这一点上很长一段时间了。
发布于 2018-03-05 07:09:04
当您在示例中遇到"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) {
// ..
}
}发布于 2018-03-05 07:11:03
无论何时开始处理新字符,count都是0,因此不会追加任何内容。您希望count在循环开始时为1,并在while(count > 0)循环后将其设置为1。你能解释一下为什么你用count = count * 10 +c-‘0’而不是count =c(这也需要修改)吗?
发布于 2021-02-27 13:41:02
您可以按如下方式解决此问题
private static String decode(String encodedString) {
String decodedString = null;
//aaabbbcccccdd
//3a3b5c2d
int n = encodedString.length();
StringBuilder sb= new StringBuilder();
for (int i = 0; i < n; i++) {
if(i+1 <n && i%2 ==0)
sb.append(repeat(Integer.parseInt(String.valueOf(encodedString.charAt(i))),encodedString.charAt(i+1)));
}
return sb.toString();
}
private static String repeat(int length, char charAt) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < length; j++) {
sb.append(charAt);
}
return sb.toString();
}https://stackoverflow.com/questions/49101408
复制相似问题