RLE Compression

时间:2015-11-01 01:40:53

标签: java loops

I have the following java code for an RLE Compression algorithm:

public static String compress (String original) {
    String compressed = "";
    char letter = 0;
    int count = 1;
    for (int i = 0; i < original.length(); i++)  {
        if (letter == original.charAt(i)) {
            count = count + 1;
        }
        else {
            compressed = compressed + letter;
            if(count != 1) {
                compressed = compressed + count;
            }
            letter = original.charAt(i);
            count = 1;
        }
    }
    compressed = compressed + letter;
    if(count != 1) {
        compressed = compressed + count;
    }
    return compressed;
}

If the input is aaaawwwweerrr

The output should be: 3a4w2e3r

The actual output is: a3w4e2r3

I tried switching

compressed = compressed + count

to

compressed = count + compressed

but when I do that the output is: 244 awer3

How should I modify the code so that the output is in the appropriate sequence?

2 个答案:

答案 0 :(得分:3)

if(count != 1){
  compressed = compressed + count;
}
compressed = compressed + letter;

首先附加count然后letter

您需要在两个地方执行此操作,第一个inside the loop和第二个after the loop完成最后一个字符。

我建议您使用StringBuilder.append()代替String连接。

public static String compress (String original) {
  StringBuilder compressed = new StringBuilder();
  char letter = 0;
  int count = 1;
  for (int i = 0; i < original.length(); i++) {
    if (letter == original.charAt(i)) {
      count = count + 1;
    }
    else {
      compressed = count !=1 ? compressed.append(count) : compressed;
      compressed.append(letter);
      letter = original.charAt(i);
      count = 1;
    }
  }

  compressed = count !=1 ? compressed.append(count) : compressed;
  compressed.append(letter);
  return compressed.toString();
}

Input : aaaawwwweerrr
Output: 4a4w2e3r

答案 1 :(得分:-2)

请参阅此代码:

public class RunLengthEncoding {

  String s1 = "aaawwweerrr" ;

  public void compressed ( String s1) {
    int count =0;
    char temp = s1.charAt(0);
    for(int i=0; i<s1.length(); i++) {
      if (s1.charAt(i) == temp) {
        count++;
      }
      else {
        System.out.print(temp + ""+ count+" ");
        count =1;
        temp = s1.charAt(i);
      }
    }
  }
  public static void main (String[] args) throws IOException {
    RunLengthEncoding obj = new RunLengthEncoding();
    obj.compressed(obj.s1);
  }
}