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.文章来源:https://www.toymoban.com/news/detail-607705.html
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文章来源地址https://www.toymoban.com/news/detail-607705.html
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 //14. Longest Common Prefix的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!