我有一个字符串“aaabbaaaavvvd”,它应该被压缩为a3b2a4v3d 但是当我运行代码时它会打印出 b3a2v4d3
奇怪的是,它以 b 开头,而不是 a
public class compression {
public String compress(String str){
char chararr[] = str.toCharArray();
StringBuilder sb = new StringBuilder();
int count=1;
char previous = chararr[0];
for(int i=1; i<chararr.length; i++) {
char current = chararr[i];
if(current == previous){
count++;
} else {
sb.append(current).append(count);
count = 1;
}
previous = current;
}
System.out.println(sb.toString());
return sb.toString();
}
public static void main(String args[]){
compression test = new compression();
String str = "aaabbaaaavvvd";
test.compress(str);
}
}
最佳答案
线路错误:
sb.append(current).append(count);
考虑一下 if 语句
if(current == previous){
count++;
} else {
sb.append(current).append(count);
count = 1;
}
当您的代码逐步执行每个字符时,仅当当前字符不等于最后一个字符(即当前字符是新的字符序列)。
逐一进行:
Index 1: previous == 'a', current == 'a', if-statement: true - increments
Index 2: previous == 'a', current == 'a', if-statement: true - increments
Index 3: previous == 'a', current == 'b', if-statement: false - prints and reset
请注意,在第三个索引上,current
是 b 而不是所需的字符 a,输出 b3
与a3
相反。
用以前的
替换附加链来修复:
if(current == previous){
count++;
} else {
sb.append(previous).append(count);
count = 1;
}
关于Java 字符串压缩打印错误的字符串。我在这里缺少什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29723077/