Skip to content

Commit a95df1b

Browse files
add problem 14 and test function
1 parent 906ff56 commit a95df1b

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

C/1-50/14-Longest-Common-Prefix.c

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
* Write a function to find the longest common prefix string amongst an array of strings.
3+
* Created by supercoderx on 2017/8/9.
4+
*/
5+
#include
6+
#include
7+
#include
8+
9+
char *longestCommonPrefix(char **strs, int strsSize) {
10+
char *str = NULL;
11+
if (strsSize == 0) {
12+
return "";
13+
}
14+
if (strsSize == 1) {
15+
return strs[0];
16+
}
17+
int lenArr[strsSize], len = 0, minLen = 0, curMinLen = 0;
18+
19+
for (int i = 0; i < strsSize; i++) {
20+
str = strs[i];
21+
lenArr[i] = 0;
22+
while (*str != '\0') {
23+
lenArr[i]++;
24+
str++;
25+
}
26+
}
27+
minLen = lenArr[0];
28+
for (int i = 1; i < strsSize; i++) {
29+
curMinLen = 0;
30+
len = lenArr[i] > minLen ? minLen : lenArr[i];
31+
for (int j = 0; j < len; j++) {
32+
if (strs[i - 1][j] != strs[i][j])
33+
break;
34+
curMinLen++;
35+
}
36+
if (curMinLen < minLen)
37+
minLen = curMinLen;
38+
}
39+
if (minLen == 0)
40+
return "";
41+
str = malloc(sizeof(char) * (minLen + 1));
42+
str = strncpy(str, strs[strsSize - 1], minLen);
43+
str[minLen] = '\0';
44+
return str;
45+
}
46+
47+
void testLongestCommonPrefix() {
48+
49+
char *s1[] = {"aa", "b"};
50+
printf("%s", longestCommonPrefix(s1, 3));
51+
}

0 commit comments

Comments
 (0)