#include <iostream>
#include <stack>
#include <unordered_map>
#include <cstdlib>
std::string encode(const std::string inputstr) {
std::string encoded_str;
std::unordered_map<char, int> str_umap;
for (int i = 0; i < inputstr.size() ; i++) {
char key = inputstr.at(i);
auto it = str_umap.find(key);
if(it == str_umap.end()) { // key not in msp
str_umap[key] = 1;
} else {
str_umap[key] += 1;
}
//Not at end of string
if (i != inputstr.size() - 1) {
//Detect if run is over
if(inputstr.at(i) != inputstr.at(i + 1)) {
if(str_umap[key] == 1) {
encoded_str += key;
} else {
encoded_str += key + std::to_string(str_umap[key]);
}
str_umap.clear();
}
} else {
if(str_umap[key] == 1) {
encoded_str += key;
} else {
encoded_str += key + std::to_string(str_umap[key]);
}
str_umap.clear();
}
}
return encoded_str;
}
std::string decode(const std::string encodedstr) {
std::string decoded_str;
char alpha = encodedstr.at(0);
decoded_str += alpha;
int num_of_times = 0;
for (int i = 1; i < encodedstr.size() ; i++) {
if(std::isdigit(encodedstr.at(i))) {
num_of_times = static_cast<char>(encodedstr.at(i)) - '0';
std::cout << num_of_times << "\n";
} else {
for (int j = 0; j < num_of_times ; j++) {
decoded_str += alpha;
}
num_of_times = 0;
alpha = encodedstr.at(i);
}
}
return decoded_str;
}
int main() {
std::string mystring = "AAAABBBAC111c";
std::cout << "Input string : " << mystring << "\n";
std::string encoded = encode(mystring);
std::cout << "Encoded string : " << encoded << "\n";
std::string decoded = decode(encoded);
std::cout << "Decoded string : " << decoded << "\n";
return 0;
}