Skip to content

Commit

Permalink
Longest commom prefix
Browse files Browse the repository at this point in the history
Signed-off-by: Leo Ma <[email protected]>
  • Loading branch information
begeekmyfriend committed Aug 19, 2017
1 parent 743ca6b commit de8ec4b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 014_longest_common_prefix/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test common_prefix.c
33 changes: 33 additions & 0 deletions 014_longest_common_prefix/common_prefix.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

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;
}

0 comments on commit de8ec4b

Please sign in to comment.