首页 > 代码库 > Longest Common Prefix

Longest Common Prefix

Write a function to find the longest common prefix string amongst an array of strings.


#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char *longestCommonPrefix(char *strs[],int n)
{
    int i,j,k;
    char *res=(char *)malloc(sizeof(char)*1000);
    char *p=strs[0];
    char *q=strs[1];
    //printf("%s,%c\n",q,q[1]);
    //printf("%s\n",p);
    if(p==NULL) return "";
    if(q==NULL) return p;
    for(i=0;p[i]!='\0' && q[i]!='\0';i++){
        if(p[i]==q[i]) res[i]=p[i];
        else break;
    }
    res[i]='\0';
    for(k=2,q=strs[k];k<n;k++){
        for(i=0;res[i]!='\0'&&strs[k][i]!='\0';i++){
            if(res[i]!=strs[k][i]) break;
        }
        res[i]='\0';
    }
    return res;
}

void main(){
    char *str[]={"abc","a","abcd"};
    char *str1[]={"a","b"};
    printf("%s\n",longestCommonPrefix(str1,2));
}


Longest Common Prefix