题目:
Write a function to find the longest common prefix string amongst an array of strings.
思路:
C程序实现:
char* longestCommonPrefix(char** strs, int strsSize) {
if(strsSize == 0) return "";
if(strsSize == 1 || strs[0][0] == '\0') return strs[0];
char* pre=malloc((strlen(strs[0])+1) * sizeof(char));
int k=0; //pre的下标
int i=0, j=0;
while(strs[0][j]!='\0'){
i = 0;
while(i<strsSize-1 && strs[i][j]==strs[i+1][j]) i++;
if(i==strsSize-1 && j>=0){
pre[k++]=strs[i][j];
j++;
}
else if(i!=strsSize-1 && j==0) return "";
else{
pre[k]='\0'; //一定不要忘记这个!!
return pre;
}
}
pre[k]='\0'; //一定不要忘记这个!!
return pre;
}