#include #include #include #include /* Sample midterm question: Design an algorithm and write code to remove the duplicate characters in a string without using any additional buffer. NOTE: One or two additional variables are fine. An extra copy of the array is not. FOLLOW UP Write the test cases for this function. */ // using NO additional buffer char* deDup(char str[]) { int i = 0,j; char ch; while((ch = str[i++] )!= '\0') { j = i; while(str[j] != '\0') { if(ch == str[j]) { while(str[j]!='\0') { str[j] = str[j+1]; j++; } i--; break; } j++; } } return str; } // using additional buffer // O(n) char* deDup2(char * str) { int len = strlen(str); int ch; bool hit[256] = { false }; ch = str[0]; hit[ch] = true; int tail = 1; for (int i = 1; i < len; ++i) { ch = str[i]; if (!hit[ch]) { str[tail] = ch; ++tail; hit[ch] = true; } } str[tail] = 0; return str; } int main(int argc, char ** argv) { if (argc != 2) { fprintf(stderr, "Usage: dedup string\n"); exit(1); } char * s1 = argv[1]; printf("%s:", s1); deDup(s1); printf("%s\n", s1); printf("\nwith boolean array:\n"); printf("%s:", s1); // deDup2(s1); printf("%s\n", s1); return 0; } /* test cases 1. String does not contain any duplicates, e.g.: abcd 2. String contains all duplicates, e.g.: aaaa 3. Null string / Empty string 4. String with all continuous duplicates, e.g.: aaabbb 5. String with non-contiguous duplicate, e.g.: abababa */