gpt4 book ai didi

java - 游程编码程序的数字在字母之前

转载 作者:行者123 更新时间:2023-11-30 03:11:33 25 4
gpt4 key购买 nike

我正在制作一个游程编码程序,用于缩短单词。即 aaabbc 变为 3a2bc

我的程序到目前为止可以运行,但不是输出 3a2bc,而是输出 a3b2c。那么如何切换当前程序呢?

代码:

public class Compress {
public static void main(String[] args) {
String word = "aaabbc";
System.out.println(compress(word));
}


public static String compress (String original){
String compressed = "";

char ch = original.charAt(0);
int counter = 1;
for (int i = 1; i < original.length(); i++) {
if (ch == original.charAt(i)) {
counter = counter + 1;
}
else {
compressed = compressed + ch;
if(counter != 1){
compressed = compressed + counter;
}
ch = original.charAt(i);
counter = 1;
}
}
compressed = compressed + ch;
if(counter != 1){
compressed = compressed + counter;
}
return compressed;
}
}

最佳答案

你所在的地方:

             else {
compressed = compressed + ch;
if(counter != 1){
compressed = compressed + counter;
}
ch = original.charAt(i);
counter = 1;
}

你应该切换前两个语句 block ,例如

             else {
if(counter != 1){
compressed = compressed + counter;
}
compressed = compressed + ch;
ch = original.charAt(i);
counter = 1;
}

顺便说一句,使用 StringBuilder 比 String 更有效

关于java - 游程编码程序的数字在字母之前,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33532318/

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