美文网首页
c语言计算最长公共前缀

c语言计算最长公共前缀

作者: 一路向后 | 来源:发表于2022-06-15 21:02 被阅读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

相关文章

  • c语言计算最长公共前缀

    1.问题描述 给你一个大小为 n 的字符串数组 strs ,其中包含n个字符串 , 编写一个函数来查找字符串数组中...

  • [数组] 14最长公共前缀 (C语言)

    题目   编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 "" 示例1: 输入:...

  • LeetCode 每日一题 [19] 最长公共前缀

    LeetCode 最长公共前缀 [简单] 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回...

  • 14. 最长公共前缀

    20180923-摘抄自14. 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,...

  • 5,最长公共前缀/数组与字符串

    最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例 1:...

  • Swift 最长公共前缀 - LeetCode

    题目: 最长公共前缀 描述: 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""...

  • leetcode探索之旅(14)

    最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。如果不存在公共前缀,返回空字符串 ""。 示例 1: ...

  • Leetcode 14 最长公共前缀

    最长公共前缀 题目 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例...

  • LeetCodeSwift 14.Longest Common

    题目 最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 示例...

  • [day4] [LeetCode] [title14,122]

    14.最长公共前缀 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串""。 示例 ...

网友评论

      本文标题:c语言计算最长公共前缀

      本文链接:https://www.haomeiwen.com/subject/fqtfvrtx.html