del*_*del 15 python algorithm dynamic-programming lcs
我试图找到3个或更多字符串的最长公共子序列.维基百科的文章很好地描述了如何为2个字符串执行此操作,但我不太确定如何将其扩展为3个或更多字符串.
有很多库可以找到2个字符串的LCS,所以我想尽可能使用其中一个.如果我有3个字符串A,B和C,找到A和B的LCS作为X是有效的,然后找到X和C的LCS,或者这是错误的方法吗?
我在Python中实现了如下:
import difflib
def lcs(str1, str2):
sm = difflib.SequenceMatcher()
sm.set_seqs(str1, str2)
matching_blocks = [str1[m.a:m.a+m.size] for m in sm.get_matching_blocks()]
return "".join(matching_blocks)
print reduce(lcs, ['abacbdab', 'bdcaba', 'cbacaa'])
Run Code Online (Sandbox Code Playgroud)
这输出"ba",但它应该是"baa".
IVl*_*lad 23
只是概括了递归关系.
对于三个字符串:
dp[i, j, k] = 1 + dp[i - 1, j - 1, k - 1] if A[i] = B[j] = C[k]
max(dp[i - 1, j, k], dp[i, j - 1, k], dp[i, j, k - 1]) otherwise
Run Code Online (Sandbox Code Playgroud)
应该很容易概括为更多的字符串.
我只需要为作业做这个,所以这是我在 python 中的动态编程解决方案,它非常有效。它是 O(nml),其中 n、m 和 l 是三个序列的长度。
该解决方案的工作原理是创建一个 3D 数组,然后枚举所有三个序列来计算最长子序列的路径。然后您可以回溯数组以从其路径重建实际子序列。
因此,您将数组初始化为全零,然后枚举三个序列。在枚举的每个步骤中,您要么在最长子序列的长度上加一个(如果有匹配),要么只是继承上一步枚举中的最长子序列。
枚举完成后,您现在可以回溯数组以根据您采取的步骤重建子序列。即,当您从数组中的最后一个条目向后移动时,每次遇到匹配项时,您都会在任何序列中查找它(使用数组中的坐标)并将其添加到子序列中。
def lcs3(a, b, c):
m = len(a)
l = len(b)
n = len(c)
subs = [[[0 for k in range(n+1)] for j in range(l+1)] for i in range(m+1)]
for i, x in enumerate(a):
for j, y in enumerate(b):
for k, z in enumerate(c):
if x == y and y == z:
subs[i+1][j+1][k+1] = subs[i][j][k] + 1
else:
subs[i+1][j+1][k+1] = max(subs[i+1][j+1][k],
subs[i][j+1][k+1],
subs[i+1][j][k+1])
# return subs[-1][-1][-1] #if you only need the length of the lcs
lcs = ""
while m > 0 and l > 0 and n > 0:
step = subs[m][l][n]
if step == subs[m-1][l][n]:
m -= 1
elif step == subs[m][l-1][n]:
l -= 1
elif step == subs[m][l][n-1]:
n -= 1
else:
lcs += str(a[m-1])
m -= 1
l -= 1
n -= 1
return lcs[::-1]
Run Code Online (Sandbox Code Playgroud)
要查找2个字符串A和B的最长公共子序列(LCS),您可以对角遍历二维数组,如发布的链接中所示。数组中的每个元素都对应于找到子字符串A'和B'的LCS的问题(A的行号减少,B的列号减少)。通过计算数组中所有元素的值可以解决此问题。您必须确保在计算数组元素的值时,已经解决了计算给定值所需的所有子问题。这就是为什么您对角遍历二维数组的原因。
可以缩放此解决方案以找到N个字符串之间最长的公共子序列,但这需要一种通用的方法来迭代N维数组,以便仅在元素的所有子问题都需要解决的情况下才可以到达任何元素。
除了以特殊的顺序迭代N维数组,您还可以递归地解决该问题。对于递归,保存中间解决方案很重要,因为许多分支机构都需要相同的中间解决方案。我在C#中编写了一个小示例来执行此操作:
string lcs(string[] strings)
{
if (strings.Length == 0)
return "";
if (strings.Length == 1)
return strings[0];
int max = -1;
int cacheSize = 1;
for (int i = 0; i < strings.Length; i++)
{
cacheSize *= strings[i].Length;
if (strings[i].Length > max)
max = strings[i].Length;
}
string[] cache = new string[cacheSize];
int[] indexes = new int[strings.Length];
for (int i = 0; i < indexes.Length; i++)
indexes[i] = strings[i].Length - 1;
return lcsBack(strings, indexes, cache);
}
string lcsBack(string[] strings, int[] indexes, string[] cache)
{
for (int i = 0; i < indexes.Length; i++ )
if (indexes[i] == -1)
return "";
bool match = true;
for (int i = 1; i < indexes.Length; i++)
{
if (strings[0][indexes[0]] != strings[i][indexes[i]])
{
match = false;
break;
}
}
if (match)
{
int[] newIndexes = new int[indexes.Length];
for (int i = 0; i < indexes.Length; i++)
newIndexes[i] = indexes[i] - 1;
string result = lcsBack(strings, newIndexes, cache) + strings[0][indexes[0]];
cache[calcCachePos(indexes, strings)] = result;
return result;
}
else
{
string[] subStrings = new string[strings.Length];
for (int i = 0; i < strings.Length; i++)
{
if (indexes[i] <= 0)
subStrings[i] = "";
else
{
int[] newIndexes = new int[indexes.Length];
for (int j = 0; j < indexes.Length; j++)
newIndexes[j] = indexes[j];
newIndexes[i]--;
int cachePos = calcCachePos(newIndexes, strings);
if (cache[cachePos] == null)
subStrings[i] = lcsBack(strings, newIndexes, cache);
else
subStrings[i] = cache[cachePos];
}
}
string longestString = "";
int longestLength = 0;
for (int i = 0; i < subStrings.Length; i++)
{
if (subStrings[i].Length > longestLength)
{
longestString = subStrings[i];
longestLength = longestString.Length;
}
}
cache[calcCachePos(indexes, strings)] = longestString;
return longestString;
}
}
int calcCachePos(int[] indexes, string[] strings)
{
int factor = 1;
int pos = 0;
for (int i = 0; i < indexes.Length; i++)
{
pos += indexes[i] * factor;
factor *= strings[i].Length;
}
return pos;
}
Run Code Online (Sandbox Code Playgroud)
我的代码示例可以进一步优化。许多要缓存的字符串是重复的,而有些是重复的,只添加了一个附加字符。当输入字符串变大时,这将使用比所需更多的空间。
输入时:“ 666222054263314443712”,“ 5432127413542377777”,“ 6664664565464057425”
返回的LCS是“ 54442”