题目:编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入: [“flower”,“flow”,“flight”]
输出: “fl”
示例 2:
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/longest-common-prefix
思路:这道题本质上是找每个字符串都包含的,从头开始的连续子串。写这道题只需要以第一个字符串为模板,逐个寻找其余字符串里都包含的子串即可。
代码:
char * longestCommonPrefix(char ** strs, int strsSize)
{ //字符串个数
char *s;
int i=1,j,len=0;
if(strsSize==0)
return "";//空串
for(j=0;strs[0][j]!='\0';j++)
len++;//这里假设第一个字符串就是共同的子串
while(i<strsSize)//故从第二个字符串开始
{
j=0;
while(strs[0][j]==strs[i][j]&&strs[i][j]!='\0')
j++;//找相同字符串,得到长度
if(j<len)
len=j;//毎经历一次循环,更新一次共同子串长度
i++;
}
s=(char*)malloc((len+1)*sizeof(char));
for(i=0;i<len;i++)
s[i]=strs[0][i];
s[i]='\0';
return s;
}