#include #include #include /* Sample midterm question: Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures? */ // assume ASCII characters // Cost: O(n) plus space for boolean array. bool unique(const char * str){ int len = strlen(str); int c; bool letters[256] = { false }; for(int i = 0; i < len; i++) { c = str[i]; if (letters[c]) { return false; } else { letters[c] = true; } } return true; } // if we assume only lower case letters, we can use // an integer as a bit vector. // Cost: O(n) plus a single int for bit vector. bool uniquelower(const char * str){ int len = strlen(str); int c; int letters = 0; for(int i = 0; i < len; i++) { c = str[i] - 'a'; if (letters & 1 << c) { return false; } else { letters |= 1 << c; } } return true; } /* Other methods: 1. Check every char of the string with every other char of the string for duplicate occurrences. This will take O(n^2) time and no space. 2. If we are allowed to destroy the input string, we could sort the string in O(n log n) time and then linearly check the string for neighboring characters that are identical. */ int main(int argc, char ** argv) { char * s1 = "thisisatest"; char * s2 = "swift"; char * s3 = "AaBb .&Zz"; printf("boolean array:\n"); printf("%s: %d\n", s1, unique(s1)); printf("%s: %d\n", s2, unique(s2)); printf("%s: %d\n", s3, unique(s3)); printf("\nbit vector:\n"); printf("%s: %d\n", s1, uniquelower(s1)); printf("%s: %d\n", s2, uniquelower(s2)); return 0; }