题解 | #最长公共前缀#C+暴力解法

最长公共前缀

http://www.nowcoder.com/practice/28eb3175488f4434a4a6207f6f484f47

看没人用C做这个题,写一下自己的思路

  1. 找到最短字符串
  2. 用最短字符串和其它字符串比较,找到公共的子序列
  3. 时间复杂度:N+N*M
char* Com_str12(char* s1, char* s2, int n) {
    char* s = (char*)malloc(sizeof(char) * 400);
    int i = 0, j = 0;
    if (s1[0] != s2[0]) {
        s = "";
        return s;
    }
    while (i < n) {
        if (s1[i] == s2[i]) {
            s[i] = s1[i];
        } else {
            break;
        }
        i++;
    }
    return s;

}
char* longestCommonPrefix(char** strs, int strsLen ) {
    // write code here
    //暴力解法思路,先找出最短的字符串的长度,然后截取最长看是否相等,如果不是,就减一
    int i = 0, min_len = 5001, j = 0, max = 5001, len1 = 0, g = 0;
    //char* s1 = (char*)malloc(sizeof(char) * 5000);
    char* s2 = (char*)malloc(sizeof(char) * 400);//需要提前申请地址
    char* s3 = (char*)malloc(sizeof(char) * 400);

    if (strsLen == 0 || strs == NULL) {

        return "";
    }
    if (strsLen == 1) {
        return strs[0];
    }
    for (i = 0; i < strsLen; i++) {//找最短字符串
        len1 = strlen(strs[i]);
        if ( len1 < min_len) {
            min_len = strlen(strs[i]);
           // strcpy(s1, strs[i]);
            g = i;
        }
    }
    for (i = 0; i < strsLen ; i++) {//和最短字符串比较
        if (i != g) {
            s2 = Com_str12(strs[i], strs[g], min_len);
            if (max > strlen(s2)) {
                max = strlen(s2);
                strcpy(s3,s2);
            }
        }

    }
    return s3;
}



全部评论

相关推荐

牛客83700679...:简历抄别人的,然后再投,有反馈就是简历不行,没反馈就是学历不行,多投多改只要技术不差机会总会有的
点赞 评论 收藏
分享
06-15 02:05
已编辑
南昌航空大学 数据分析师
Eason三木:你如果想干技术岗,那几个发公众号合唱比赛的经历就去掉,优秀团员去掉,求职没用。然后CET4这种不是奖项,是技能,放到下面的专业技能里或者单独列一个英语能力。 另外好好改改你的排版,首行缩进完全没有必要,行间距好好调调,别让字和标题背景黏在一起,你下面说能做高质量PPT你得展现出来啊,你这简历排版我用PPT做的都能比你做的好。 然后自我评价,你如果要干数据工程师,抗压能力强最起码得有吧。
简历中的项目经历要怎么写
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务