运行-长度编码程序数字在字母之前

Run-length encoding program have number come before letter

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

你应该交换前两个语句块,比如

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

顺便说一句,为此使用 StringBuilder 比使用 String

更有效