编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 ""
。
示例 1:
输入:strs = ["flower","flow","flight"] 输出:"fl"
示例 2:
输入:strs = ["dog","racecar","car"] 输出:"" 解释:输入不存在公共前缀。
提示:
1 <= strs.length <= 200
0 <= strs[i].length <= 200
strs[i]
仅由小写英文字母组成
char*longestCommonPrefix(char **strs, int strsSize)
{
int i, j, max = strlen(strs[0]), n = 0;
if (strsSize == 0)
return "";
for (i = 1; i < strsSize; i++)
if (strlen(strs[i]) > max)
max = strlen(strs[i]);
int const m = max;
char *ch = (char *) malloc(m + 1); // Allocate memory for the common prefix
for (j = 0; j < m; j++) {
for (i = 0; i < strsSize - 1; i++) {
if (strs[i][j] != strs[i + 1][j])
goto quit;
}
n++;
}
quit:
if (n != 0) {
for (i = 0; i < n; i++)
ch[i] = strs[0][i];
ch[n] = '\0'; // Null-terminate the string
return ch;
} else {
//free(ch); // Free the allocated memory
return "";
}
}