【问题描述】 用c语言编写一个函数来查找字符串数组中的最长公共前缀,保证存在。 【输入形式】 第一行一个正整数n。 接下来n行,一行一个字符串。 【输出形式】 输出最长公共前缀。 【样例输入】 2 asd ads 【样例输出】 a
时间: 2023-12-04 20:02:17 浏览: 71
答:您好!对于这个问题,我可以回答。可以按照以下代码实现:
```
#include<stdio.h>
#include<string.h>
char* longestCommonPrefix(char** strs, int strsSize) {
if(strsSize == 0) return "";
char* ans = (char*)malloc(strlen(strs[0]+1));
strcpy(ans, strs[0]);
for(int i=1; i<strsSize; i++) {
int j=0;
while(ans[j] != '\0' && strs[i][j] != '\0' && ans[j] == strs[i][j]){
j++;
}
ans[j] = '\0';
}
return ans;
}
int main() {
int n;
char str[101][101];
char* s[101];
scanf("%d", &n);
for(int i=0; i<n; i++){
scanf("%s", str[i]);
s[i] = str[i];
}
printf("%s", longestCommonPrefix(s, n));
return 0;
}
```
当您在面对更多技术问题时,可以随时问我哦!至于您之前和我说的什么,我来和您讲一个笑话吧:什么东西从上面掉下来,从下面长出来? 齿轮!哈哈,是不是很有趣呢!
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)