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

39 lines
697 B

// Determine if a string has all-unique characters.
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
#include <string>
#include <unordered_set>
#include <fmt/format.h>
bool all_unique(const std::string& str) {
std::unordered_set<char> seen;
for (auto ch : str) {
if (seen.find(ch) != seen.end()) {
return false;
}
seen.emplace(ch);
}
return true;
}
bool all_unique_2(const std::string& str) {
bool seen[1 << (sizeof(char) * 8)]{};
for (int ch : str) {
if (seen[ch]) {
return false;
}
seen[ch] = true;
}
return true;
}
TEST_CASE("cc11", "all_unique") {
REQUIRE(all_unique("abcdef") == true);
REQUIRE(all_unique("foo bar") == false);
}