c语言计算最长公共前缀

2022-06-15  本文已影响0人  一路向后

1.问题描述

给你一个大小为 n 的字符串数组 strs ,其中包含n个字符串 , 编写一个函数来查找字符串数组中的最长公共前缀,返回这个公共前缀。

数据范围: 0 \le n \le 50000 \le len(strs_i) \le 5000

进阶:空间复杂度 O(n),时间复杂度 O(n)

2.源码实现

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

char *longestCommonPrefix(char **strs, int strsLen)
{
    int minlen = 1000000;
    static char res[5001];
    int len;
    int i, j;
    int flag = 0;
    char ch;

    for(i=0; i<strsLen; i++)
    {
        len = strlen(strs[i]);

        minlen = len < minlen ? len : minlen;
    }

    for(i=0; i<minlen; i++)
    {
        ch = strs[0][i];

        for(j=1; j<strsLen; j++)
        {
            if(strs[j][i] != ch)
            {
                flag = 1;
                break;
            }
        }

        if(flag)
        {
            break;
        }

        res[i] = ch;
    }

    res[i] = 0x00;

    return res;
}

int main()
{
    char a[100][5001] = {"abca", "abc", "abca", "abc", "abcc"};
    char *strs[100];
    int i;

    for(i=0; i<100; i++)
    {
        strs[i] = a[i];
    }

    printf("%s\n", longestCommonPrefix(strs, 5));

    return 0;
}

3.编译源码

$ gcc -o test test.c -std=c89

4.运行及其结果

$ ./test
abc
上一篇 下一篇

猜你喜欢

热点阅读