-2

I compressed my binary string and it's outputting 3131 for 6 1s(111111) which represents the character 'p' from this code by @tigrang I found in this link.

     public static String compress_string(String inp) {
        String compressed = "";
        Pattern pattern = Pattern.compile("([\\w])\\1*");
        Matcher matcher = pattern.matcher(inp);
        while(matcher.find()) {
           String group = matcher.group();
           if (group.length() > 1) compressed += group.length() + "";
           compressed += group.charAt(0);
        }
        return compressed;
    }

Now I need to uncompress this string "3131" and make it output 111111. How can I do this without using a loop? And is there any way to compress it even more, for eg: outputting 61 instead of 3131?

TheFlyBiker 420
  • 69
  • 1
  • 13

1 Answers1

1

How about something like:

public static String compress_string(String inp) {
    String compressed = "";
    Pattern pattern = Pattern.compile("([\\w])\\1*");
    Matcher matcher = pattern.matcher(inp);
    while (matcher.find()) {
        String group = matcher.group();
        if (group.length() > 1) compressed += group.length() + "";
        compressed += group.charAt(0);
    }
    return compressed;
}

public static String decompress_string(String inp) {
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < inp.length(); i++) {
        char ch = inp.charAt(i);
        if (ch == '1') {
            s.append('1');
        } else {
            int count = ch - '0';
            String repeat = "" + inp.charAt(++i);
            s.append(String.join("", Collections.nCopies(count, repeat)));
        }
    }
    return s.toString();
}

public void test(String[] args) throws Exception {
    String test = "111111";
    String compressed = compress_string(test);
    String decompressed = decompress_string(compressed);
    System.out.println("test = '" + test + "' compressed = '" + compressed + "' decompressed = '" + decompressed + "'");
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • This works but the problem is I'm already inside a for loop and i want to minimize the time complexity but i'll give this a try and get back on you. – TheFlyBiker 420 Apr 11 '18 at 14:10