对于这个问题,网上有其他答案。但是,我需要一些帮助来确定我编写的代码有什么不正确。
问题: 编写一个函数来查找字符串数组中最长的公共前缀字符串。如果没有公共前缀,则返回一个空字符串""。
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.
以下 C 代码是我针对此问题提出的解决方案,但在某些情况下不起作用。如果有人告诉我这段代码有什么问题,我将不胜感激。
下面的代码通过了一些对其进行的测试。 (即["flower","flow","flight"]
)
但是,其他情况(例如 ["ab", "a"]
)会导致程序抛出堆缓冲区溢出错误。
char * longestCommonPrefix(char ** strs, int strsSize){
if(strlen(strs[0]) == 0) return "";
if(strsSize == 1) return strs[0];
char* finale = calloc(strlen(*strs), sizeof(char));
strcpy(finale, "");
int ptr = 0;
char* thechar = strs[0][ptr];
int tocontinue = 1;
while(thechar != '\0') {
for (int i = 1; i < strsSize; i++) {
if (strs[i][ptr] == '\0' || strs[i][ptr] != thechar) {
tocontinue = 0;
}
}
if (!tocontinue) {
break;
}
finale[strlen(finale)] = thechar;
finale[strlen(finale) + 1] = '\0';
ptr++;
thechar = strs[0][ptr];
}
finale = realloc(finale, sizeof(finale));
return
finale;
}
提前致谢。