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 ""
.
Example 1:
Input: ["flower","flow","flight"] Output: "fl"
Example 2:
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) {
char *temp ;
int j,i;
if(strsSize<0)
return "";
temp =strs[0];
for(i=1;i<strsSize;i++)
{
j=0;
while(temp[j]==strs[i][j]&&temp[j]&&strs[i][j])
j++;
temp[j] ='\0';
}
return temp;
}