From b137d99a961d4dda872cd230c85d1ad4ed066bee Mon Sep 17 00:00:00 2001 From: Nick Chambers Date: Sat, 1 Jun 2024 20:33:49 -0500 Subject: [PATCH] Determine if a string has any duplicate characters --- c/unique.c | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 c/unique.c diff --git a/c/unique.c b/c/unique.c new file mode 100644 index 0000000..02b7105 --- /dev/null +++ b/c/unique.c @@ -0,0 +1,43 @@ +// not uniq(1) + +#include +#include +#include + +const char *unique(const char *str, const char **dup) { + const char *alphabet[26] = { NULL }; + + for(; *str; str += 1) { + uint8_t pos = tolower(*str) - 'a'; + + if(pos >= 0 && pos <= 25) { + if(alphabet[pos]) { + *dup = str; + return alphabet[pos]; + } else { + alphabet[pos] = str; + } + } + } + + return NULL; +} + +int main(int argc, char **argv) { + const char *str = ""; + + if(argc > 1) { + str = argv[1]; + } + + const char *dup = NULL; + const char *idx = unique(str, &dup); + + if(dup) { + uint8_t idx_spacing = (int) (idx - str) + 1; + uint8_t dup_spacing = (int) (dup - str) - idx_spacing + 1; + printf("%s\n%*s%*s\n", str, idx_spacing, "^", dup_spacing, "^"); + } + + return 0; +}