How to compress and decompress repeated string characters by storing the repeated length (RLE) in TypeScript

1 Answer

0 votes
// ---------------------------------------------------------
//   Compress: turn "aaabbcccc" into "a3b2c4"
//   This is run-length encoding (RLE)
// ---------------------------------------------------------
function compress(s: string): string {
    if (!s) {
        return "";   // Edge case: empty string
    }

    const out: string[] = [];   // Result string (array for efficiency)
    let count: number = 1;              // Count of repeated characters

    // Start from index 1 and compare with previous character
    for (let i: number = 1; i <= s.length; i++) {

        // If still repeating the same character, increase count
        if (i < s.length && s[i] === s[i - 1]) {
            count++;
        } else {
            // Character changed OR reached end of string
            out.push(s[i - 1]);      // Add the character
            out.push(String(count)); // Add how many times it repeated
            count = 1;               // Reset counter
        }
    }

    return out.join("");
}


// ---------------------------------------------------------
//   Decompress: turn "a3b2c4" into "aaabbcccc"
//   Reads a letter, then reads digits, expands them.
// ---------------------------------------------------------
function decompress(s: string): string {
    const out: string[] = [];     // Result string
    let currentChar: string | null = null;  // The character being processed
    let num: string[] = [];    // Digits representing the count

    for (const c of s) {

        if (/[A-Za-z]/.test(c)) {   // Found a letter
            // If we already have a previous letter + number, expand it
            if (currentChar !== null && num.length > 0) {
                const count = Number(num.join(""));
                out.push(currentChar.repeat(count));
            }

            currentChar = c;       // Start new character
            num = [];           // Reset number buffer

        } else if (/\d/.test(c)) { // Found a digit
            num.push(c);        // Build multi-digit number
        }
    }

    // Handle the last character + number pair
    if (currentChar !== null && num.length > 0) {
        const count = Number(num.join(""));
        out.push(currentChar.repeat(count));
    }

    return out.join("");
}


function main(): void {
    const s = "wwwwwwwwwwwwbwwwwwwwwwwbbbwwwwwwccccwwwwwwwwwwww";

    const c: string = compress(s);
    const d: string = decompress(c);

    console.log("Original:   ", s);
    console.log("Compressed: ", c);
    console.log("Decompressed:", d);
}

main();



/*
run:

Original:    wwwwwwwwwwwwbwwwwwwwwwwbbbwwwwwwccccwwwwwwwwwwww
Compressed:  w12b1w10b3w6c4w12
Decompressed: wwwwwwwwwwwwbwwwwwwwwwwbbbwwwwwwccccwwwwwwwwwwww

*/

 



answered 1 day ago by avibootz

Related questions

...