Critiques (even pedantic ones) are welcome.
bool unique_chars(std::string &s) {
if (s.length()>256) return false;
std::bitset<256> bs;
for (auto &c:s) {
if (bs.test(c)) return false;
bs.set(c);
}
return true;
}
EDIT 1:
for (auto &c:s) { //OLD
for (unsigned char c:s) { //NEW
Reasoning:
char
can be either signed or unsigned- if signed then
bs[]
can be out of bounds - casting to unsigned eliminates issue as negative values will wrap
EDIT 2:
This string is to be made up of characters from the standard ASCII character set, i.e. fitting into a 1 byte char
.
EDIT 3:
Renamed function / added test harness with examples. Function parameter changed to const, as string not being modified.
#include <iostream>
#include <bitset>
bool areCharsUnique(const std::string &s) {
if (s.length()>256) return false;
std::bitset<256> bs;
for (unsigned char c:s) {
if (bs.test(c)) return false;
bs.set(c);
}
return true;
}
int main() {
std::string s1 = "hi there";
std::string s2 = "hey man";
std::cout << areCharsUnique(s1) << std::endl; //0
std::cout << areCharsUnique(s2) << std::endl; //1
return 0;
}