-
Notifications
You must be signed in to change notification settings - Fork 119
/
14.c
48 lines (40 loc) · 869 Bytes
/
14.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* longestCommonPrefix(char** strs, int strsSize) {
char *ans;
if (strsSize == 0) {
ans = "";
return ans;
}
else {
ans = malloc(strlen(strs[0]));
strcpy(ans, strs[0]);
}
int i, j;
for (j = 0; ans[j] != '\0'; j++) {
for (i = 1; i < strsSize; i++) {
if (strs[i][j] != ans[j]) {
goto OUT;
}
}
}
OUT:
ans[j] = '\0';
return ans;
}
int main() {
char *strs[20] = {
"abcde",
"abceawsdffd",
"abcsdas",
"abcefwfdf",
"abcd",
"abc"
};
char *s = longestCommonPrefix(strs, 6);
printf("%s\n", s);
s = longestCommonPrefix(NULL, 0);
printf("%s\n", s);
return 0;
}