Description:
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string “”.
Example1:
Input: [“flower”,“flow”,“flight”]
Output: “fl”
Example2:
Input: [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.
Note:
All given inputs are in lowercase letters a-z.
提交代码:
char* longestCommonPrefix(char** strs, int strsSize) {
int i, p = 0, flag = 1;
char* prefix = (char*)malloc(10000 * sizeof(char));
char tmp;
while (flag&&strs[0][p]!='\0')
{
//设置当前第一个字符串的第p个字符为标杆
tmp = strs[0][p];
for (i = 1; i < strsSize; i++)
{
if (strs[i][p] != tmp||strs[i][p]=='\0')
{
flag = 0;
break;
}
}
//退出for循环表示已经轮完一遍所有字符和标杆字符一样
if(flag!=0)
prefix[p++] = tmp;
}
prefix[p] = '\0';
return prefix;
}
运行结果: