Problem
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.
Example 1:
Input: [“flower”,“flow”,“flight”]
Output: “fl”
Example 2:
Input: [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
solution
char* longestCommonPrefix(char** strs, int strsSize) {
char* prefix = (char*)malloc(10000 * sizeof(char));
char tmp;
int flag = 1;
int n = 0;
int min = strlen(*strs);
for (int j = 1; j < strsSize; j++) {
if (min > strlen(*(strs + j))) {
min = strlen(*(strs + j));
}
}
if (min == 0) return "";
while (flag && *(*strs + n) != '\0') {
for (int i = 1; i < strsSize; i++) {
if (*(*strs + n) != *(*(strs + i) + n)) {
flag = 0;
break;
}
}
if (flag == 1) {
*(prefix + n) = *(*strs + n);
n++;
}
}
*(prefix + n + 1) = '\0';
return prefix;
}