Run-length decompression

前端 未结 6 1539
天涯浪人
天涯浪人 2021-01-26 17:25

CS student here. I want to write a program that will decompress a string that has been encoded according to a modified form of run-length encoding (which I\'ve already written c

6条回答
  •  温柔的废话
    2021-01-26 18:04

    A simple regex will do.

    final Matcher m = Pattern.compile("(\\D)(\\d+)").matcher(input);
    final StringBuffer b = new StringBuffer();
    while (m.find()) 
      m.appendReplacement(b, replicate(m.group(1), Integer.parseInt(m.group(2))));
    m.appendTail(b);
    

    where replicate is

    String replicate(String s, int count) {
      final StringBuilder b = new StringBuilder(count);
      for (int i = 0; i < count; i++) b.append(s);
      return b.toString();
    }
    

提交回复
热议问题