cxx17/cc11.cc

40 lines
697 B
C++

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