javadecodingrun-length-encoding

Java run length decoding (expanding a compressed string)


public static String decompressString (String text) {
    int count = 0;
    StringBuilder result = new StringBuilder () ;
    for (int i = 0; i < text.length(); i++) {
        char c = text.charAt(i);
        if (Character.isDigit(c)) {
            count = count * 10 + c - '0';
        } else { 
            while (count >0){ 
                result.append(c);
                count--;
            }
        }

    }
    return result.toString();
}

The program is supposed to take in a run length encoded string from the main method such as 5A5Bcd and return the string in a run length decoded format. 5A5Bcd -> AAAAABBBBBcd. The problem i am running into is that the code seems to ignore characters that are not preceeded by a digit. In the example above i am returning AAAAABBBBB instead of AAAAABBBBBcd; the 'c' and 'd' are not preceeded by a digit and therefore arent recognized. Any ideas, I have been stuck at this point for quite some time now.


Solution

  • Your count variable is not going to be nonzero when you encounter the "c" and "d" characters in your example, because it will have been decremented to zero after processing the "5B".

    The simplest fix I see in your code is to add a check before the while loop:

    if (Character.isDigit(c)) {
        // ...
    } else {
        if (count == 0) {
            // Single-run-length characters have an implicit "1" prepended
            count = 1;
        }
        while (count > 0) {
            // ..
        }
    }