【发布时间】:2016-08-22 19:51:10
【问题描述】:
例子:
{ 54, 87, 23, 87, 45, 67, 7, 85, 65, 65, 3, 4, 55, 76, 65, 64, 5, 6, 4, 54, 45强>, 6, 4 };
{ 76, 57, 65, 3, 4, 55, 76, 65, 64, 5, 6, 4, 54, 45, 8, 65, 66, 57, 6, 7 , 7, 56, 6, 7, 44, 57, 8, 76, 54, 67 };
基本上,我有两个字节[],需要在两者中找到最大相同的字节序列。
我已经尝试了显而易见的事情并编写了一些代码来暴力破解结果:
var bestIndex = 0;
var bestCount = 0;
for (var i1 = 0; i1 + bestCount < data1.Length; i1++)
{
var currentCount = 0;
for (var i2 = 0; i2 < data2.Length; i2++)
{
if (data1[i1 + currentCount] == data2[i2])
{
currentCount++;
if (i1 + currentCount == data1.Length)
{
bestCount = currentCount;
bestIndex = i1;
break;
}
}
else
{
if (currentCount > bestCount)
{
bestCount = currentCount;
bestIndex = i1;
}
currentCount = 0;
}
}
if (currentCount > bestCount)
{
bestCount = currentCount;
bestIndex = i1;
}
}
但是,在我的应用程序中,字节数组会大得多,甚至可以达到 GB。所以基本上我需要一个关于如何提高效率的提示/代码。
【问题讨论】:
-
对我来说看起来像 np 完整
-
@Dmitry:OP 可能想要一个公共子字符串,而不是子序列。
-
这可以用 DP 在 O(nm) 中完成,如en.wikipedia.org/wiki/Longest_common_substring_problem中所述
-
@Steve:我相信 Dmitry 发布了子序列的链接,Gerardo 的链接更简单。