1

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

1 回答 1

2

你在哪里:

             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 效率更高

于 2015-11-04T21:32:03.940 回答