Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures?
#include <iostream> #include <string.h> using namespace std; bool checkUnique(char *str); bool checkUnique(char *str) { // string length is less than 256 if(strlen(str) > 256) return false; int charArray[256] = {}; for(int i=0;i<strlen(str);i++) { charArray[(int)str[i]]++; if(charArray[str[i]] > 1) return false; } return true; } int main(int argc, const char * argv[]) { char ch[]= "qazwsxedcrfvyhnujm"; if(checkUnique(ch)) cout<<"UNIQUE"<<endl; else cout<<"NOT UNIQUE"<<endl; return 0; }
Time Complexity: O(n)
Space Complexity: O(1)
Initialize an array in C/C++
in C:
in C++: