【leetcode】14-Longest Common Prefix

  本篇博客解析 14-Longest Common Prefix


 

一、题目

  Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "".

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

  示例:

 

 

二、分析

  传入的参数是一个二维数组,每行是一个字符串。我们可以以第一个字符串作为基准,逐个比较各元素。

  如果第一个字符串为空,则直接返回。

  如果所有字符串中的对应下标元素均一致,则这个元素是公共前缀,添加到结果数组中。

 

三、代码

 1 char * longestCommonPrefix(char ** strs, int strsSize){
 2     int i = 0, count = 0;
 3     char *result = malloc(sizeof(char) * 200);
 4     memset(result, 0, sizeof(result));
 5     
 6     while (strsSize) {
 7         char c = strs[0][count];
 8         
 9         if (c == '\0')
10             break;
11         
12         for (i = 1 ; i < strsSize ; i++)
13         {
14             if (c != strs[i][count])
15                 break;
16         }
17         
18         if (i == strsSize)
19             result[count++] = c;
20         else
21             break;
22     }
23     
24     result[count] = '\0';
25     
26     return result;
27 }

 

posted @ 2020-06-21 17:44  Albert-陌尘  阅读(167)  评论(0编辑  收藏  举报