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.
// Longest_Common_Prefix.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<stdlib.h>
#include<stdio.h>
#include<malloc.h>
#include<string.h>
int main()
{
char* longestCommonPrefix(char** strs, int strsSize);
char **strs;
//带双星号的指针型数据赋值方法,先动态申请内存,在逐个赋值,接受变量赋值
strs = (char**)malloc(sizeof(char*) * 3);
char str1[] = "flower";
char str2[] = "flow";
char str3[] = "flight";
strs[0] = str1;
strs[1] = str2;
strs[2] = str3;
printf("%s",longestCommonPrefix(strs,3));
return 0;
}
/*带**的当成二维数组来使用即可
*/
char* longestCommonPrefix(char** strs, int strsSize) {
int i, j,flag=0;
//如果有返回值,又在函数内定义,需要动态申请内存空间
char *temp = (char *)malloc(sizeof(char)*100);
for(i=0;i<strlen(strs[0]);i++){
for(j=1;j<strsSize;j++)
if(strs[j][i]!=strs[0][i]||i>=strlen(strs[j])){
flag=1;
break;
}
if(flag)break;
temp[i] = strs[0][i];
}
temp[i] = '\0';
return temp;
}