llllmz

导航

14. 最长公共前缀c

bool judge(char* s1,char* s2,int n){
    for(int i=0;i<n;i++){
        if(s1[i]!=s2[i]) return false;
    }
    return true;
}

char* longestCommonPrefix(char** strs, int strsSize) {
    int count=strlen(strs[0]);
    for(int i=1;i<strsSize;i++){
        while(count>0 && !judge(strs[0],strs[i],count)) count--;
        if(count==0) return ""; 
    }
    char* array=(char*)malloc(sizeof(char)*(count+1));
    for(int i=0;i<count;i++){
        array[i]=strs[0][i];
    }    
    array[count]=0;
    return array;
}

 

posted on 2024-03-21 19:47  神奇的萝卜丝  阅读(2)  评论(0编辑  收藏  举报