#include #include #include #include #include /* Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures? */ bool nodup(char * s){ int chars[256] = {0}; int len = strlen(s); printf("s = %s\n", s); int val; for (int i = 0; i < len; i++){ val = s[i]; printf("%c = %d\n", s[i], val); if (chars[val]) return false; chars[val]++; } return true; } bool nodup2(char * s){ int len = strlen(s); printf("s = %s\n", s); int val; for (int i = 0; i < len; i++){ val = s[i]; printf("%c = %d\n", s[i], val); for (int j = i; j < len; j++){ if (s[j] == val) return false; } } return true; } /* Write code to reverse a C-Style String. (C-String means that “abcd” is represented as five characters, including the null character.) */ void reverse(char * str){ char * end = str; char tmp; if (str) { while (*end) { ++end; } --end; while (str < end) { tmp = *str; *str++ = *end; *end-- = tmp; } } } /* 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. */ char * dedup(char * str){ char tmp; int len = strlen(str); for (int i = 0; i < len; i++) { tmp = str[i]; for (int j = i; j < len; j++){ if (str[j] == tmp) { len--; for (int k = j; k < len; k++){ str[k] = str[k+1]; } } } } } int main(int argc, char ** argv){ if (argc < 2) { fprintf(stderr, "Usage: %s string+\n", argv[0]); exit(1); } for (int i = 1; i< argc; i++) { printf("String: %s has %s\n", argv[i], (nodup(argv[i])) ? " no dups" : " some dups"); printf("String: %s has %s\n", argv[i], (nodup2(argv[i])) ? " no dups" : " some dups"); printf("Reverse of %s == ", argv[i]); reverse(argv[i]); printf(" %s\n", argv[i]); printf("Dedup of %s == ", argv[i]); dedup(argv[i]); printf(" %s\n", argv[i]); } }