行程编码程序的编号在

时间:2015-11-04 21:26:36

标签: java string loops run-length-encoding

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

1 个答案:

答案 0 :(得分: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

更有效率