Skip to content

Instantly share code, notes, and snippets.

@shantanugoel
Last active April 8, 2018 13:19
Show Gist options
  • Save shantanugoel/cbcbc09cf6b823ee281f492a7afb4b4f to your computer and use it in GitHub Desktop.
Save shantanugoel/cbcbc09cf6b823ee281f492a7afb4b4f to your computer and use it in GitHub Desktop.
#include <iostream>
#include <string>
std::string compress(const std::string &input) {
auto read_idx = 0, count = 0;
bool sequence_start = true;
std::string output;
while (read_idx < input.size()) {
char c = input[read_idx];
if (std::isalpha(static_cast<unsigned char>(c))) {
if (sequence_start) {
output.push_back(c);
read_idx++;
sequence_start = false;
count = 1;
} else {
if (c != output.back()) {
output.append(std::to_string(count));
sequence_start = true;
} else {
count++;
read_idx++;
}
}
} else {
throw std::invalid_argument("Invalid character in input string");
}
}
output.append(std::to_string(count));
if (output.size() > input.size()) {
throw std::runtime_error("Cannot Compress");
}
return output;
}
int main() {
std::string input;
while (1) {
std::cout << "Enter String to compress: ";
std::getline(std::cin, input);
try {
std::string output;
std::cout << compress(input) << "\n";
} catch (const std::exception &e) {
std::cout << "Error: " << e.what() << "\n";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment