LearnFrenzy
Sign in Take a free test

std::string · String Programs · Question 8

Compress a string by counting repeated characters in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

Compress strings such as "aabcccccaaa" to "a2b1c5a3"; if the compressed form is not shorter, return the original.

Solution
main.cpp
#include <iostream>
#include <string>

std::string compress(const std::string& s) {
    std::string out;
    for (std::size_t i = 0; i < s.size(); ) {
        std::size_t j = i;
        while (j < s.size() && s[j] == s[i]) ++j;
        out += s[i];
        out += std::to_string(j - i);
        i = j;
    }
    return out.size() < s.size() ? out : s;
}

int main() {
    for (std::string s : {"aabcccccaaa", "abcdef", "zzzzzzzzzzz", ""})
        std::cout << '[' << s << "] -> [" << compress(s) << "]\n";
    return 0;
}

Output Verified by compiling and running

[aabcccccaaa] -> [a2b1c5a3]
[abcdef] -> [abcdef]
[zzzzzzzzzzz] -> [z11]
[] -> []

Each run of equal characters becomes the character plus its length. For strings without repeats the "compressed" form doubles the length, so the original is returned.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links