Run-length decompression

前端 未结 6 1535
天涯浪人
天涯浪人 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();
    }
    
    0 讨论(0)
  • 2021-01-26 18:12

    I think you can divide chars in numeric and not numeric symbols.

    When you find a numeric one (>0 and <9) you look to the next and choose to enlarge you number (current *10 + new) or to expand your string

    0 讨论(0)
  • 2021-01-26 18:18

    Presuming that you're not asking about the parsing, you can convert a string like "10" into an integer like this:

    int i = Integer.parseInt("10");
    
    0 讨论(0)
  • 2021-01-26 18:26

    Not sure whether this is one efficient way, but just for reference

    for (int i=0;i<your_string.length();i++)
        if (your_string.charAt(i)<='9' && your_string.charAt(i)>='0')
            integer_begin_location = i;
    
    0 讨论(0)
  • 2021-01-26 18:28

    Here is a working implementation in python. This also works fine for 2 or 3 or multiple digit numbers

    inputString="a1b3s22d4a2b22"
    inputString=inputString+"\0"                 //just appending a null char
    charcount=""
    previouschar=""
    outputString=""
    
    for char in inputString:
      if char.isnumeric():
        charcount=charcount+char  
      else:
        outputString=outputString
        if previouschar:
          outputString=outputString+(previouschar*int(charcount))   
        charcount=""
        previouschar=char
        
    print(outputString) // outputString= abbbssssssssssssssssssssssffffddaabbbbbbbbbbbbbbbbbbbbbb
    
    0 讨论(0)
  • 2021-01-26 18:31

    Assuming that the uncompressed data does never contain digits: Iterate over the string, character by character until you get a digit. Then continue until you have a non-digit (or end of string). The digits inbetween can be parsed to an integer as others already stated:

    int count = Integer.parseInt(str.substring(start, end));
    
    0 讨论(0)
提交回复
热议问题