String Compression

1.6 String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2blc5a3. If the "compressed" string would not become smaller than the original string, your method should return the original string.

#include <iostream>
#include <string>

using namespace std;

// inplace
// O(1) space
// O(n)

void replace(string &s, int &i, int &alphaCount) {
    s.replace(i + 1, alphaCount -1 , to_string(alphaCount));
    //i--;
    alphaCount = 1;
}

// assuming string is sorted, or at least not scattered
string firstCompression(string s) {
    int length = s.length();
    string copy = s;
    int alphaCount = 1;
    for (int i = s.length() - 1; i >= 0; i--) {
        if (i == 0) {
            replace(s, i, alphaCount);
        }
        else if (s.at(i) == s.at(i - 1)) {
            alphaCount++;
        }
        else {
            // replace(position, length, string)
            replace(s, i, alphaCount);
        }
    }
    if (length < s.length) {
        return copy;
    }
    return s;

}


int main()
{
    cout << firstCompression("aaaabbbbbbbbbddddccccfff");
}

Last updated