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

1 Answer

0 votes
#include <iostream>
#include <string>
#include <cctype>

/* ---------------------------------------------------------
   Compress: turn "aaabbcccc" into "a3b2c4"
   This is run-length encoding (RLE)
   --------------------------------------------------------- */
std::string compress(const std::string &s) {
    if (s.empty()) return "";   // Edge case: empty string

    std::string out;            // Result string
    int count = 1;              // Count of repeated characters

    // Start from index 1 and compare with previous character
    for (size_t i = 1; i <= s.size(); i++) {

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

/* ---------------------------------------------------------
   Decompress: turn "a3b2c4" into "aaabbcccc"
   Reads a letter, then reads digits, expands them.
   --------------------------------------------------------- */
std::string decompress(const std::string &s) {
    std::string out;            // Result string
    char currentChar = '\0';    // The character being processed
    std::string number;         // Digits representing the count

    for (char c : s) {

        if (std::isalpha(static_cast<unsigned char>(c))) { // Found a letter
            // If we already have a previous letter + number, expand it
            if (currentChar != '\0' && !number.empty()) {
                out.append(std::stoi(number), currentChar);
            }
            currentChar = c;    // Start new character
            number.clear();     // Reset number buffer
        }
        else if (std::isdigit(static_cast<unsigned char>(c))) { // Found a digit
            number += c;        // Build multi-digit number
        }
    }

    // Handle the last character + number pair
    if (currentChar != '\0' && !number.empty()) {
        out.append(std::stoi(number), currentChar);
    }

    return out;
}

int main() {
    std::string s = "wwwwwwwwwwwwbwwwwwwwwwwbbbwwwwwwccccwwwwwwwwwwww";

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

    std::cout << "Original:   " << s << std::endl;
    std::cout << "Compressed: " << c << std::endl;
    std::cout << "Decompressed: " << d << std::endl;
}


/*
run:

Original:   wwwwwwwwwwwwbwwwwwwwwwwbbbwwwwwwccccwwwwwwwwwwww
Compressed: w12b1w10b3w6c4w12
Decompressed: wwwwwwwwwwwwbwwwwwwwwwwbbbwwwwwwccccwwwwwwwwwwww

*/

 



answered 3 hours ago by avibootz
edited 1 hour ago by avibootz
...