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/cc12.cc

34 lines
830 B

// Determine if a string has all-unique characters.
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <experimental/string_view>
#include <string>
#include <unordered_map>
using string_view = std::experimental::string_view;
auto count(string_view str) {
std::unordered_map<char, int> c;
for (auto ch : str) {
// default value is zero.
c[ch] += 1;
}
return c;
}
bool is_permutation(string_view lhs, string_view rhs) {
// unordered_map does elementwise comparison.
return count(lhs) == count(rhs);
}
TEST_CASE("cc12", "is_permutation") {
REQUIRE(is_permutation("abc", "abc") == true);
REQUIRE(is_permutation("abc", "cba") == true);
REQUIRE(is_permutation("abc", "def") == false);
REQUIRE(is_permutation("aabbbc", "abacbb") == true);
REQUIRE(is_permutation("aabbbc", "abacb") == false);
}