Last active
August 29, 2015 13:56
-
-
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?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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