cxx17/cc16.cc

43 lines
847 B
C++

// Determine if a string is one edit away from another.
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <fmt/format.h>
#include <experimental/string_view>
#include <string>
using string_view = std::experimental::string_view;
std::string compress(string_view in) {
char last = '\0';
int count = 0;
std::stringstream out;
for (auto ch : in) {
if (ch != last) {
if (count != 0) {
out << last << count;
}
last = ch;
count = 0;
}
count++;
}
if (count != 0) {
out << last << count;
}
auto compressed = out.str();
return (compressed.length() < in.length()) ? compressed : std::string(in);
}
TEST_CASE("cc16", "compress") {
CHECK(compress("aabcccccaaa") == "a2b1c5a3");
CHECK(compress("aabcccccaaaaaaaab") == "a2b1c5a8b1");
CHECK(compress("abcdef") == "abcdef");
}