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 “”.

 

Example 1:

Input: strs = [“flower”,“flow”,“flight”]
Output: “fl”

Example 2:

Input: strs = [“dog”,“racecar”,“car”]
Output: “”
Explanation: There is no common prefix among the input strings.

Constraints:

  • 1 <= strs.length <= 200
  • 0 <= strs[i].length <= 200
  • strs[i] consists of only lowercase English letters.

From: LeetCode
Link: 14. Longest Common Prefix


Solution:

Ideas:
In this code, we first check if the array of strings is empty. If it is, we return an empty string. Then, for each character in the first string, we compare it with the corresponding character in every other string. If we find a character that doesn’t match or we reach the end of any of the strings, we return the common prefix found so far. If we traverse the entire first string without finding any non-matching characters, we return the first string as the common prefix.
Code:
char * longestCommonPrefix(char ** strs, int strsSize){
    if(strsSize == 0) return "";
    
    for(int index = 0; index < strlen(strs[0]); index++){
        for(int i = 1; i < strsSize; i++){
            if(index == strlen(strs[i]) || strs[i][index] != strs[0][index]){
                char* res = (char*)malloc(sizeof(char) * (index + 1));
                strncpy(res, strs[0], index);
                res[index] = '\0';
                return res;
            }
        }
    }
    
    char* res = (char*)malloc(sizeof(char) * (strlen(strs[0]) + 1));
    strncpy(res, strs[0], strlen(strs[0]));
    res[strlen(strs[0])] = '\0';
    return res;
}

你可能感兴趣的:(LeetCode,leetcode,算法,c语言)