问题描述
我试图将我用 C++ 编写的代码用于解决一些基本问题,然后用其他语言重写,以便更加熟悉这些其他语言的语法和库函数。
我目前正在处理 leetcode 中的一个问题,我知道我可以找到该问题的解决方案,但想在此之前提出我自己的可行解决方案。
这个基本问题是在字符串数组中找到最长的前缀。就像我说的,我正在使用我的 C++ 工作解决方案并尝试翻译成另一种语言。在这种情况下,我试图将解决方案转换为 C。
我使用的是基本的累加器方法。然而,与我的 C++ 版本不同,C 中的版本返回整个第一个作品,而不是前缀。例如,如果数组是 ["run","rude","running"],那么它应该返回“ru”,而是返回“run”。
我认为这与我复制、附加或分配值的方式有关,但目前我看不出问题出在哪里。
非常感谢任何想法和帮助。
这是我的代码:
// Variables
char * longestCommonPrefix(char ** strs,int stRSSize){
char *result = (char *) malloc(sizeof(char));
char current = ' ';
// Find smallest word
int smallestWordSize = 201;
int size = sizeof(strs) / sizeof *strs;
for (int index = 0; index < size; ++index) {
if (strlen(strs[index]) < smallestWordSize) {
smallestWordSize = strlen(strs[index]);
}
}
// For case where there is only one element
if(size == 1){
result = strs[0];
}
// Create result string
else {
for (int i = 0; i < smallestWordSize; ++i) {
strncpy(current,strs[0][i],1);
for (int j = 1; j < size; ++j) {
if (current != strs[j][i]) {
return result;
}
}
strncat(result,current,1);
}
}
return result;
}
是的,我意识到我没有使用参数 stRSSize,因为在 C++ 解决方案中,它没有该参数,我正在尝试从一种语言到另一种语言的直接翻译。
>解决方法
所以,在解决这个问题之后,我终于想出了一个解决方案。在这个过程中,我确实发现了更简单的解决方案,但正如我所说,我希望这与我在 C++ 中所做的累加器方法相匹配。这就是我想出来的,对于那些可能感兴趣的人。
char * longestCommonPrefix(char ** strs,int strsSize){
char current = ' ';
int smallestWordSize = 201;
for (int index = 0; index < strsSize; ++index) {
if (strlen(strs[index]) < smallestWordSize) {
smallestWordSize = strlen(strs[index]);
}
}
char *result = malloc(sizeof(char) * smallestWordSize +1);
result[0] = '\0';
if(strsSize == 0) {
return result;
}
if(strsSize == 1){
result = strs[0];
return result;
}
int i = 0;
bool match = true;
for (i = 0; i < smallestWordSize && match; ++i) {
current = strs[0][i];
for (int j = 1; j < strsSize && match; ++j) {
if (current != strs[j][i]) {
i--;
match = false;
}
}
}
if (i > 0){
strncat(result,strs[0],i);
}
else {
result = "";
return result;;
}
return result;
}