From de8ec4b7f3578bc42e3ba6e5745f1caa2056fe55 Mon Sep 17 00:00:00 2001 From: Leo Ma Date: Sat, 19 Aug 2017 16:52:16 +0800 Subject: [PATCH] Longest commom prefix Signed-off-by: Leo Ma --- 014_longest_common_prefix/Makefile | 2 ++ 014_longest_common_prefix/common_prefix.c | 33 +++++++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 014_longest_common_prefix/Makefile create mode 100644 014_longest_common_prefix/common_prefix.c diff --git a/014_longest_common_prefix/Makefile b/014_longest_common_prefix/Makefile new file mode 100644 index 0000000..1003ec6 --- /dev/null +++ b/014_longest_common_prefix/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test common_prefix.c diff --git a/014_longest_common_prefix/common_prefix.c b/014_longest_common_prefix/common_prefix.c new file mode 100644 index 0000000..aa1c63a --- /dev/null +++ b/014_longest_common_prefix/common_prefix.c @@ -0,0 +1,33 @@ +#include +#include +#include + +static char* longestCommonPrefix(char** strs, int strsSize) +{ + int i, capacity = 50, count = 0; + char *result = malloc(50); + bool go_on = true; + while (strsSize > 0 && go_on) { + char temp = strs[0][count]; + for (i = 1; i < strsSize; i++) { + if (temp != strs[i][count]) break; + } + if (i == strsSize && temp != '\0') { + if (count + 1 + 1 >= capacity) { + capacity *= 2; + result = realloc(result, capacity + 1); + } + result[count++] = temp; + } else { + go_on = false; + } + } + result[count++] = '\0'; + return result; +} + +int main(int argc, char **argv) +{ + printf("%s\n", longestCommonPrefix(argv + 1, argc - 1)); + return 0; +}