gpt4 book ai didi

Java 字符串压缩打印错误的字符串。我在这里缺少什么?

转载 作者:行者123 更新时间:2023-12-01 11:38:50 25 4
gpt4 key购买 nike

我有一个字符串“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

请注意,在第三个索引上,currentb 而不是所需的字符 a,输出 b3a3相反。

以前的替换附加链来修复:

if(current == previous){
count++;
} else {
sb.append(previous).append(count);
count = 1;
}

关于Java 字符串压缩打印错误的字符串。我在这里缺少什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29723077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com