我正在制作一个用于缩短单词的行程编码程序。即 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;
}
}