Skip to content

Instantly share code, notes, and snippets.

@frank4565
Last active August 29, 2015 13:56
Show Gist options
  • Save frank4565/8929901 to your computer and use it in GitHub Desktop.
Save frank4565/8929901 to your computer and use it in GitHub Desktop.
1.1 Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
#include<iostream>
const unsigned NUM_CHAR = 256;
bool hasAllUniqueChar (std::string s)
{
if (s.size() > NUM_CHAR) return false;
// init array
unsigned array[NUM_CHAR/sizeof(int)+1] = {};
// check if the char has appeared
for (auto c : s) {
int idx = c/sizeof(int);
unsigned flag = 1 << c%sizeof(int);
if ((array[idx] & flag) != 0) return false;
array[idx] |= flag;
}
return true;
}
int main(int argc, char *argv[])
{
std::string s = "";
std::cin >> s;
std::cout << hasAllUniqueChar(s) << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment