14. Longest common prefix (leetcode) – C language

Time:2022-5-16

Method 1: horizontal traversal method

//Transverse traversal method
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int getCommonPrefix(char *prev, char *next) {
  int len = strlen(prev) < strlen(next) ? strlen(prev) : strlen(next);
  int k = 0;
  while (k < len) {
    if (prev[k] != next[k]) {
      return k;
    }
    k++;
  }
  return k;
}

char *longestCommonPrefix(char **strs, int strsSize) {
  if (strsSize <= 0) {
    return "";
  }
  int commonPrefixLen = strlen(strs[0]);
  char *commonPrefix = (char *)malloc((commonPrefixLen + 1) * sizeof(char));
  strncpy(commonPrefix, *strs, commonPrefixLen);
  //Add an empty character to the end of the string, otherwise an array access error will occur, resulting in heap overflow
  //After looking for this problem for a long time, I finally found that strncpy just copies characters and does not automatically add empty characters to the end of the string
  *(commonPrefix + commonPrefixLen) = '
//Transverse traversal method
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int getCommonPrefix(char *prev, char *next) {
int len = strlen(prev) < strlen(next) ? strlen(prev) : strlen(next);
int k = 0;
while (k < len) {
if (prev[k] != next[k]) {
return k;
}
k++;
}
return k;
}
char *longestCommonPrefix(char **strs, int strsSize) {
if (strsSize <= 0) {
return "";
}
int commonPrefixLen = strlen(strs[0]);
char *commonPrefix = (char *)malloc((commonPrefixLen + 1) * sizeof(char));
strncpy(commonPrefix, *strs, commonPrefixLen);
//Add an empty character to the end of the string, otherwise an array access error will occur, resulting in heap overflow
//After looking for this problem for a long time, I finally found that strncpy just copies characters and does not automatically add empty characters to the end of the string
*(commonPrefix + commonPrefixLen) = '\0';
for (int i = 1; i < strsSize; i++)
{
int len = getCommonPrefix(commonPrefix, *(strs + i));
//Initialize the string to be completely empty, and then copy the characters without worrying about adding empty characters at the end
memset(commonPrefix, '\0', commonPrefixLen + 1);
if (len <= 0) {
return commonPrefix;
}
strncpy(commonPrefix, *(strs + i), len);
}
return commonPrefix;
}
int main(void) {
char *strs[] = {"flower", "flow", "flight"};
printf("%s\n", longestCommonPrefix(strs, 3));
}
'; for (int i = 1; i < strsSize; i++) { int len = getCommonPrefix(commonPrefix, *(strs + i)); //Initialize the string to be completely empty, and then copy the characters without worrying about adding empty characters at the end memset(commonPrefix, '
//Transverse traversal method
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int getCommonPrefix(char *prev, char *next) {
int len = strlen(prev) < strlen(next) ? strlen(prev) : strlen(next);
int k = 0;
while (k < len) {
if (prev[k] != next[k]) {
return k;
}
k++;
}
return k;
}
char *longestCommonPrefix(char **strs, int strsSize) {
if (strsSize <= 0) {
return "";
}
int commonPrefixLen = strlen(strs[0]);
char *commonPrefix = (char *)malloc((commonPrefixLen + 1) * sizeof(char));
strncpy(commonPrefix, *strs, commonPrefixLen);
//Add an empty character to the end of the string, otherwise an array access error will occur, resulting in heap overflow
//After looking for this problem for a long time, I finally found that strncpy just copies characters and does not automatically add empty characters to the end of the string
*(commonPrefix + commonPrefixLen) = '\0';
for (int i = 1; i < strsSize; i++)
{
int len = getCommonPrefix(commonPrefix, *(strs + i));
//Initialize the string to be completely empty, and then copy the characters without worrying about adding empty characters at the end
memset(commonPrefix, '\0', commonPrefixLen + 1);
if (len <= 0) {
return commonPrefix;
}
strncpy(commonPrefix, *(strs + i), len);
}
return commonPrefix;
}
int main(void) {
char *strs[] = {"flower", "flow", "flight"};
printf("%s\n", longestCommonPrefix(strs, 3));
}
', commonPrefixLen + 1); if (len <= 0) { return commonPrefix; } strncpy(commonPrefix, *(strs + i), len); } return commonPrefix; } int main(void) { char *strs[] = {"flower", "flow", "flight"}; printf("%s\n", longestCommonPrefix(strs, 3)); }

14. Longest common prefix (leetcode) - C language

  • Time complexity: O (MN), where m is the average length of strings in the string array and N is the number of strings. In the worst case, each character of each string in the string array is compared once.
  • Space complexity: O (1). The additional space complexity used is constant.

Method 2: longitudinal traversal method

//Longitudinal traversal method
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *longestCommonPrefix(char **strs, int strsSize)
{
  if (strsSize <= 0) {
    return "";
  }
  int len = strlen(strs[0]);
  char *commonPrefix = (char *)malloc((len + 1) * sizeof(char));
  memset(commonPrefix, '
//Longitudinal traversal method
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *longestCommonPrefix(char **strs, int strsSize)
{
if (strsSize <= 0) {
return "";
}
int len = strlen(strs[0]);
char *commonPrefix = (char *)malloc((len + 1) * sizeof(char));
memset(commonPrefix, '\0', len + 1);
for (int i = 0; i < len; i++)
{
for (int j = 0; j < strsSize - 1; j++) {
//I = = strlen (STRs [J]) is used to prevent array access from going out of bounds
if (i == strlen(strs[j]) || strs[j][i] != strs[j + 1][i])
{
strncpy(commonPrefix, strs[0], i);
return commonPrefix;
}
}
}
return strs[0];
}
int main(void) {
char *strs[] = {"flower","flow","flight"};
printf("%s\n", longestCommonPrefix(strs, 3));
}
', len + 1); for (int i = 0; i < len; i++) { for (int j = 0; j < strsSize - 1; j++) { //I = = strlen (STRs [J]) is used to prevent array access from going out of bounds if (i == strlen(strs[j]) || strs[j][i] != strs[j + 1][i]) { strncpy(commonPrefix, strs[0], i); return commonPrefix; } } } return strs[0]; } int main(void) { char *strs[] = {"flower","flow","flight"}; printf("%s\n", longestCommonPrefix(strs, 3)); }

14. Longest common prefix (leetcode) - C language

  • Time complexity: O (MN), M is the average length of strings in the string array, and N is the number of strings. In the worst case, each character of each string in the string array is compared once.
  • Space complexity: O (1). The additional space complexity used is constant.

Method 3: divide and conquer

//Divide and conquer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *commonPrefix(char *leftStr, char *rightStr)
{
  int len = strlen(leftStr) < strlen(rightStr) ? strlen(leftStr) : strlen(rightStr);
  char *str = (char *)malloc((len + 1) * sizeof(char));
  memset(str, '
//Divide and conquer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *commonPrefix(char *leftStr, char *rightStr)
{
int len = strlen(leftStr) < strlen(rightStr) ? strlen(leftStr) : strlen(rightStr);
char *str = (char *)malloc((len + 1) * sizeof(char));
memset(str, '\0', len + 1);
for (int i = 0; i < len; i++)
{
if (leftStr[i] != rightStr[i])
{
strncpy(str, leftStr, i);
return str;
}
}
strncpy(str, leftStr, len);
return str;
}
char *recurse(char **strs, int start, int end)
{
if (start == end)
{
return strs[start];
}
int mid = (end - start) / 2 + start;
char *leftStr = recurse(strs, start, mid);
char *rightStr = recurse(strs, mid + 1, end);
return commonPrefix(leftStr, rightStr);
}
char *longestCommonPrefix(char **strs, int strsSize)
{
if (strsSize <= 0)
{
return "";
}
return recurse(strs, 0, strsSize - 1);
}
int main(void)
{
char *strs[] = {"dog", "racecar", "car"};
printf("%s\n", longestCommonPrefix(strs, 3));
}
', len + 1); for (int i = 0; i < len; i++) { if (leftStr[i] != rightStr[i]) { strncpy(str, leftStr, i); return str; } } strncpy(str, leftStr, len); return str; } char *recurse(char **strs, int start, int end) { if (start == end) { return strs[start]; } int mid = (end - start) / 2 + start; char *leftStr = recurse(strs, start, mid); char *rightStr = recurse(strs, mid + 1, end); return commonPrefix(leftStr, rightStr); } char *longestCommonPrefix(char **strs, int strsSize) { if (strsSize <= 0) { return ""; } return recurse(strs, 0, strsSize - 1); } int main(void) { char *strs[] = {"dog", "racecar", "car"}; printf("%s\n", longestCommonPrefix(strs, 3)); }

14. Longest common prefix (leetcode) - C language

  • Time complexity: O (MN), where m is the average length of strings in the string array and N is the number of strings. The recurrence formula of time complexity is t (n) = 2 ⋅ t (2n) + O (m). Through calculation, t (n) = O (MN).
  • Spatial complexity: O (mlogn), where m is the average length of strings in the string array and N is the number of strings. The space complexity mainly depends on the number of layers of recursive calls. The maximum number of layers is logn. Each layer needs m space to store the returned results.

Method 4: binary search

//Binary search
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int getMinLen(char **strs, int strsSize) 
{
  int minLen = strlen(strs[0]);
  for (int i = 1; i < strsSize; i++) {
    if (strlen(strs[i]) < minLen)
    {
      minLen = strlen(strs[i]);
    }
  }
  return minLen;
}

int isCommonPrefix(char **strs, int strsSize, int mid) {
  for (int i = 0; i < strsSize - 1; i++) {
    if (strncmp(strs[i], strs[i + 1], mid) != 0) {
      return 0;
    }
  }
  return 1;
}

char *longestCommonPrefix(char **strs, int strsSize)
{
  if (strsSize <= 0) {
    return "";
  }
  int minLen = getMinLen(strs, strsSize);
  char *commonPrefix = (char *)malloc((minLen + 1) * sizeof(char)); 
  memset(commonPrefix, '
//Binary search
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getMinLen(char **strs, int strsSize) 
{
int minLen = strlen(strs[0]);
for (int i = 1; i < strsSize; i++) {
if (strlen(strs[i]) < minLen)
{
minLen = strlen(strs[i]);
}
}
return minLen;
}
int isCommonPrefix(char **strs, int strsSize, int mid) {
for (int i = 0; i < strsSize - 1; i++) {
if (strncmp(strs[i], strs[i + 1], mid) != 0) {
return 0;
}
}
return 1;
}
char *longestCommonPrefix(char **strs, int strsSize)
{
if (strsSize <= 0) {
return "";
}
int minLen = getMinLen(strs, strsSize);
char *commonPrefix = (char *)malloc((minLen + 1) * sizeof(char)); 
memset(commonPrefix, '\0', minLen + 1);
int left = 1;
int right = minLen;
while (left <= right) {
int mid = (left + right) / 2;
if (isCommonPrefix(strs, strsSize, mid))
{
left = mid + 1;
} else {
right = mid - 1;
}
}
strncpy(commonPrefix, strs[0], right);
return commonPrefix;
}
int main(void)
{
char *strs[] = {"flower", "flow", "flight"};
printf("%s\n", longestCommonPrefix(strs, 3));
}
', minLen + 1); int left = 1; int right = minLen; while (left <= right) { int mid = (left + right) / 2; if (isCommonPrefix(strs, strsSize, mid)) { left = mid + 1; } else { right = mid - 1; } } strncpy(commonPrefix, strs[0], right); return commonPrefix; } int main(void) { char *strs[] = {"flower", "flow", "flight"}; printf("%s\n", longestCommonPrefix(strs, 3)); }

14. Longest common prefix (leetcode) - C language

  • Time complexity: O (mnlogm), where m is the minimum length of strings in the string array and N is the number of strings. The number of iterations of binary search is O (logm). Each iteration needs to compare Mn characters at most, so the total time complexity is O (mnlogm).
  • Space complexity: O (1). The additional space complexity used is constant.

Recommended Today

JS generate guid method

JS generate guid method https://blog.csdn.net/Alive_tree/article/details/87942348 Globally unique identification(GUID) is an algorithm generatedBinaryCount Reg128 bitsNumber ofidentifier , GUID is mainly used in networks or systems with multiple nodes and computers. Ideally, any computational geometry computer cluster will not generate two identical guids, and the total number of guids is2^128In theory, it is difficult to make two […]