- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0014-longest-common-prefix.c
31 lines (28 loc) · 965 Bytes
/
0014-longest-common-prefix.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
/*
14. Longest Common Prefix
First submitted: September 30, 2024
This solution: November 25, 2024
Runtime: 0 ms (beats 100.00%)
Memory: 8.03 MB (beats 55.00%)
*/
char*longestCommonPrefix(char**strs, intstrsSize) {
if (strsSize==1) return*strs; // only one string
char**strsEnd=strs+strsSize;
// length of shortest string is longest possible prefix
unsigned charlen_shortest=255;
for (char**p=strs; p!=strsEnd; ++p ) {
unsigned charsize=0;
for (char*q=*p; *q!='\0'; ++q, ++size) ;
if (size<len_shortest) len_shortest=size;
}
char*prefix=calloc(len_shortest+1, sizeof(char));
for (unsigned chari=0; i<len_shortest; i++) {
for (char**p=strs; p!=strsEnd; ++p ) {
char*str=*p;
// not equal, prefix ends here
if (str[i] !=strs[0][i]) returnprefix;
}
prefix[i] =strs[0][i];
}
returnprefix;
}