1 题目
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/5c2667ceee824d61aa2c43b1f12de127.png)
2 函数实现
char* longestCommonPrefix(char** strs, int strsSize) {
if (strsSize == 0) {
char* result = (char*)malloc(1);
result[0] = '\0';
return result;
}
for (int i = 0; i < strlen(strs[0]); i++) {
char currentChar = strs[0][i];
for (int j = 1; j < strsSize; j++) {
if (i >= strlen(strs[j]) || strs[j][i] != currentChar) {
char* result = (char*)malloc(i + 1);
strncpy(result, strs[0], i);
result[i] = '\0';
return result;
}
}
}
return _strdup(strs[0]);
}
3 完整测试代码
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
char* longestCommonPrefix(char** strs, int strsSize) {
if (strsSize == 0) {
char* result = (char*)malloc(1);
result[0] = '\0';
return result;
}
for (int i = 0; i < strlen(strs[0]); i++) {
char currentChar = strs[0][i];
for (int j = 1; j < strsSize; j++) {
if (i >= strlen(strs[j]) || strs[j][i] != currentChar) {
char* result = (char*)malloc(i + 1);
strncpy(result, strs[0], i);
result[i] = '\0';
return result;
}
}
}
return _strdup(strs[0]);
}
int main() {
char* strings[] = { "flower", "flow", "flight" };
int size = sizeof(strings) / sizeof(strings[0]);
char* result = longestCommonPrefix(strings, size);
printf("最长公共前缀是:%s\n", result);
free(result);
return 0;
}