leetcode_5. longest common prefix

  • Longest common prefix : Write a function to find the longest common prefix string array. If there is no common prefix, it returns an empty string "."
示例 1:

输入: ["flower","flow","flight"]
输出: "fl"

示例 2:

输入: ["dog","racecar","car"]
输出: ""
解释: 输入不存在公共前缀。

说明: 所有输入只包含小写字母 a-z 。
  • I wrote out more than one hour written, but the author always stuck with for a long time to find the bug did not find (toss two hours), temporarily abandoned.
  • The following is a positive solution, and my thinking is similar, but relatively small points, not a bug
char *longestCommonPrefix(char **strs, int strsSize)
{
  if (strsSize == 0)
  {
    return "";
  }
  if (strsSize == 1)
    return *strs;
  int len = 0;
  for (int i = 0; i < strlen(strs[0]); i++)
  {
    if (strs[0][i] == strs[1][i] && strs[0][i]!='\0')
      len++;
    else
      break;
  }
  for (int i = 1; i < strsSize - 1; i++)
  {
    if(len>strlen(strs[i+1]))
      len = strlen(strs[i + 1]);
    for (int j = len - 1; j >= 0; j--)
    {
      if (strs[i][j] != strs[i + 1][j])
        len = j;
    }
    if (len == 0)
      break;
  }
  char *result = (char *)malloc((len + 1) * sizeof(char));
  strncpy(result, strs[0], len);
  result[len] = '\0';
  return result;
}
  • The following is a bug in the code needs to be improved:
char * longestCommonPrefix(char ** strs, int strsSize){
    int n=0,tag;
    char *a=NULL;
    if(strsSize==0) return "";
    for(int j=0;(*(strs))[j]!='\0';j++)
    {
        for(int i=1;i<strsSize;i++)
        {
        	if((*(strs))[j]==(*(strs+i))[j])
        	{
        		tag=1;
        	}
        	else tag=0;
        }
        if(tag==1)
        {
        	a=(char *) realloc(a, sizeof(char)*(n+1));
        	a[n]=(*(strs))[j];
	        //printf("%c",a[n]);
	        n++;
        }
        else
        {
        	if(n==0) return "";
        	else 
			{
				a[n]='\0';
				break;
			}
        }
    }
    return a;
}
Published 77 original articles · won praise 19 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_42932834/article/details/95232145