【发布时间】:2019-01-16 06:39:43
【问题描述】:
我目前正在处理一项任务,我必须找到一种方法来输出两个字符串的最长公共子序列。在我发现此代码的实现的所有其他地方,它们都有一个相似之处:多个数组使用非常量变量进行初始化,我一直认为这是不允许的。当我试图编译程序时,我得到了一个错误。像这样的代码应该如何编译?
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
//Prints the Longest common subsequence
void printLCS(char *s1, char *s2, int m, int n);
/* Driver program to test above function */
int main()
{
char s1[] = "ABCBDAB";
char s2[] = "BDCABA";
printLCS(s1, s2, strlen(s1), strlen(s2));
return 0;
}
void printLCS(char *s1, char *s2, const int m, const int n)
{
int L[m + 1][n + 1];
//Building L[m][n] as in algorithm
for (int i = 0; i <= m; i++)
{
for (int j = 0; j <= n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (s1[i - 1] == s2[j - 1])
L[i][j] = L[i - 1][j - 1] + 1;
else
L[i][j] = max(L[i - 1][j], L[i][j - 1]);
}
}
//To print LCS
int index = L[m][n];
//charcater array to store LCS
char LCS[index + 1];
LCS[index] = '\0'; // Set the terminating character
//Stroing characters in LCS
//Start from the right bottom corner character
int i = m, j = n;
while (i > 0 && j > 0)
{
//if current character in s1 and s2 are same, then include this character in LCS[]
if (s1[i - 1] == s2[j - 1])
{
LCS[index - 1] = s1[i - 1]; // Put current character in result
i--; j--; index--; // reduce values of i, j and index
}
// compare values of L[i-1][j] and L[i][j-1] and go in direction of greater value.
else if (L[i - 1][j] > L[i][j - 1])
i--;
else
j--;
}
// Print the LCS
cout << "LCS of " << s1 << " and " << s2 << " is " << endl << LCS << endl;
}
特别是数组L和数组LCS的声明。
对不起,如果这段代码是一团糟,我并没有在这里发布。任何帮助将不胜感激。
【问题讨论】:
-
如果您的问题指定了输入大小的最大限制,只需使数组大小不变。不过,您必须小心不要在堆栈上创建大型数组。您也可以使用
std::vector,这将是最佳实践。 -
这就是我开始编写自己的程序的过程,我主要是想知道上面的代码应该如何编译。
-
GCC 扩展 - 使用
-pedantic编译。
标签: c++ arrays multidimensional-array variable-length-array lcs