编写一个函数来查找字符串数组中的最长公共前缀。
如果不存在公共前缀,返回空字符串 “”。
示例 1:
输入: [“flower”,“flow”,“flight”]
输出: “fl”
示例 2:
输入: [“dog”,“racecar”,“car”]
输出: “”
解释: 输入不存在公共前缀。
来源:力扣(LeetCode)
char * longestCommonPrefix(char ** strs, int strsSize){
int i;
char *a,*b,*temp;
a=strs[0];
if(!strsSize)
return “”;
for(i=1;i<strsSize;i++){
temp=a; //每次temp都需要重新赋值,否则值可能为‘\0’而不能再次进入while循环
b=strs[i];
while(*temp!=’\0’&&*b!=’\0’){
if(*temp!=*b){
*temp=’\0’; //若不相等则使该位地址所在空间为‘\0’,达到修改目的。
break;
}
temp++;
b++;
}
if(*b==’\0’)
a=strs[i];
}
return a;
}