cc19: added a solution.

master
Michael Hope 6 years ago
parent 23f8be7315
commit 28e5c6ba1c
  1. 4
      CMakeLists.txt
  2. 52
      cc19.cc

@ -45,3 +45,7 @@ add_test(cc17 bin/cc17)
add_executable(cc18 cc18.cc)
target_link_libraries(cc18 ${CONAN_LIBS})
add_test(cc18 bin/cc18)
add_executable(cc19 cc19.cc)
target_link_libraries(cc19 ${CONAN_LIBS})
add_test(cc19 bin/cc19)

@ -0,0 +1,52 @@
// Test if a string is a rotation of another.
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <fmt/format.h>
#include <experimental/string_view>
#include <string>
#include <unordered_set>
using string_view = std::experimental::string_view;
bool is_rotation(string_view lhs, string_view rhs) {
// Confirm using one call to isSubstring.
// Facts:
// Must be the same length.
// Must have the same letters and counts.
// Adjacents must be the same.
// Brute force version.
for (auto it = lhs.cbegin(); it != lhs.cend(); it++) {
std::string rotated{it, size_t(lhs.cend() - it)};
rotated += std::string{lhs.cbegin(), size_t(it - lhs.cbegin())};
if (rotated == rhs) {
return true;
}
}
return false;
}
bool is_rotation_2(const std::string& lhs, const std::string& rhs) {
// Clever version: if lhs is a rotation of rhs, then lhs is a
// substring of rhs+rhs.
if (lhs.length() != rhs.length()) {
return false;
}
return (lhs + lhs).find(rhs) != std::string::npos;
}
TEST_CASE("cc19", "rotate") {
CHECK(is_rotation("waterbottle", "waterbottle") == true);
CHECK(is_rotation("waterbottle", "erbottlewat") == true);
CHECK(is_rotation("waterbottle", "erbotltewat") == false);
CHECK(is_rotation("waterbottle1", "erbottlewat1") == false);
CHECK(is_rotation_2("waterbottle", "waterbottle") == true);
CHECK(is_rotation_2("waterbottle", "erbottlewat") == true);
CHECK(is_rotation_2("waterbottle", "erbotltewat") == false);
CHECK(is_rotation_2("waterbottle1", "erbottlewat1") == false);
}
Loading…
Cancel
Save