Topic describes

Write a function to find the longest public prefix in an array of strings. Returns the empty string “” if no public prefix exists.

The sample

Example 1: Input: STRS = [“flower”,”flow”,”flight”] Output: “fl”

Example 2: Input: STRS = [“dog”,”racecar”,”car”] Output: “” Explanation: The input does not have a common prefix.

Tip: 0 <= strs.length <= 200 0 <= STRS [I]. Length <= 200 STRS [I] consists of lowercase letters only

Source: LeetCode link: leetcode-cn.com/problems/lo…

Analysis of the

  1. Requires a common prefix, then all strings must contain the common prefix
  2. Based on 1 we can choose any string as the baseline, for example the first string STRS [0] is selected as the baseline
  3. Each byte of each subsequent string is compared to each byte of STRS [0], saving the common part

implementation

char *longestCommonPrefix(char **strs, int strsSize)
{
    if (strs == NULL) {
        return "";
    }
    int num = 0;
    char *res = (char*)malloc(sizeof(char) * 200);
    memset(res, 0.200);    // If this is not initialized, there may be no terminator when res is returned, resulting in an error
    for (int i = 0; i < strlen(strs[0]); i++) {
        for (int j = 1; j < strsSize; j++) {
            if (strs[j][i] == '\ 0' || strs[0][i] ! = strs[j][i]) {return res;
            }
        }
        res[i] = strs[0][i];
    }
    return res;
}
Copy the code