Playing with C++17 via solving "Cracking the Coding Interview" questions.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cxx17/cc16.cc

42 lines
847 B

// 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");
}